Home > Back-end >  Can I use specialized template without the primary template in c
Can I use specialized template without the primary template in c

Time:10-14

I tried this but this shows an error

template<>
int add(int a, int b)
{
    return a   b;
}

But when I write the below code it works fine

template<typename T>
T add(T a, T b)
{
    return a   b;
}
template<>
int add(int a, int b)
{
    return a   b;
}

CodePudding user response:

You need a primary template declaration, otherwise the compiler wouldn't know what part of the function would be templated. But you don't need to provide a primary definition. So you can do:

template<typename T>
T add(T a, T b);

template<>
int add(int a, int b) {
    return a   b;
}

CodePudding user response:

Can I use specialized template without the primary template in c

No, specialization by definition can't exist without the primary template. We need a primary template so that we can specialize(either explicitly or partially) it for some(or all) template parameters.

  • Related