Understanding C++ template partial specialization with pointer datatype arguments

When I compile the below code, I am getting error as

template<typename T> T AddFun(T i, T j) {
    return i + j;
}

template<> T* AddFun<T*>(T* i, T* j) {
    return new T(*i + *j);
}

int main() {
    int n = AddFun<int>(10, 20);
    int i = 10, j = 20;
    int* p = AddFun<int*>(&i, &j);
}

9: error: �T� does not name a type
13: error: expected unqualified-id before �int�

If I change the prototype to

template<typename T> T* AddFun<T*>(T* i, T* j)

then I get the error as 9: error: function template partial specialization �AddFun<T*>� is not allowed.

Kindly help me to correct this problem.

You're trying to make a template specialization, which means you need to use a concrete type instead of the generic T. So you could do e.g.:

template<> int* AddFun<int*>(int* i, int* j) {
    return new int(*i + *j);
}

(Although you have other issues we won't go into, like why are you trying to add two int pointers?)

The point is, in order to specialize to a pointer type, you have to name the pointer type.

On the other hand, in your first template T can be anything, including a pointer types (which is the whole point of generic programming...) - i.e. you can use any of:

int a, b;
AddFun<int>(a, b);
AddFun<int *>(&a, &b);
// etc.

On the other hand, you may be trying to say "do this when you're passed a pointer type, do something else when you're passed another type". In this case, you need to revisit all this material as that's not how templates are used - for a start, you probably don't want the return value for your second template to be a pointer (it's just an int) so you want different behaviour - create two differently named templates, one for pointers and one for raw values:

template<typename T> T AddFun(T i, T j) {
    return i + j;
}

template<typename T> T AddFunP(T* i, T* j) {
    return *i + *j;
}

void foo()
{
    int a, b;
    AddFun<int>(a, b);
    AddFunP<int>(&a, &b);
}
1 Like