1

Here is my simple program. I tried forcing the static_cast so that the compiler knows that U is nothing but int. However, still, the template cannot instantiate the int version of my function Add.

In the future, I want to extend this template so that U and V are of different types and my program still works.

However, currently, even the same type is not working. What am I missing here?

What is the reason for the compilation error?

#include <iostream>
using namespace std;

template <typename U>
class Addable
{
    U x;
public:
    Addable(U val) : x{ val } { cout << "Constructor called" << endl; }
    template <typename T>
    U add(T y);
};

U Addable::add(T y)
{
    x += y;
    return x;
}

int main()
{
    Addable<int> A{ 10 };
    int x = A.add(static_cast<int>(10));
    cout << x;
    return 0;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • As a side note: Your `static_cast` is irrelevant to the issue, what you have. Also, have a look [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – JeJo Jul 12 '21 at 06:20

2 Answers2

4

Your template member function's definition is wrong. When you define the template member function of a template class, you need to specify the both template parameters as follows:

template <typename U>
template <typename T>
U Addable<U>::add(T y)
{
    x += y;
    return x;
}

live demo

JeJo
  • 30,635
  • 6
  • 49
  • 88
0

In order to define a template function outside of a template class. The correct one should be

template <typename U> template <typename T>
U Addable<U>::add(T y)
{
   x += y;
   return x;
}
nhatnq
  • 1,173
  • 7
  • 16