Home > database >  How to write a void function for different Structs/Containers with a template?
How to write a void function for different Structs/Containers with a template?

Time:08-19

For instance I have a function

void func(my_cont &C){
  
    C.membA = 1;
    C.membB = 2;
 
    dosomething_with(C);
}

Also what to do in the function, if I have a Struct that does not have a member B?

CodePudding user response:

This is a way to statically check for the existence of a membB member inside the template function.

template<typename T>
void func(T& C)
{
    C.membA = 1;

    if constexpr (requires() { C.membB; })
    {
        C.membB = 2;
    }
}

int main()
{
    struct A
    {
        int membA;
    };
    struct B
    {
        int membA;
        int membB;
    };
    A a;
    func(a);
    B b;
    func(b);
}

Another way to get functionality that differs per type: Using template specialization, as OP requested.

struct A
{
    int membA;
};
struct B
{
    int membA;
    int membB;
};

template<typename T> void func(T&);

template<> void func<A>(A& a) {
    a.membA = 1;
}

template<> void func<B>(B& b) {
    b.membA = 1;
    b.membB = 2;
}

int main()
{
    A a;
    func(a);
    B b;
    func(b);
}
  • Related