template<typename T> class A // template parameterization
{
private:
T t;
A(const T& v) : t(v) {}
};
class B
{
template<typename T>
B(const T& v)
{
std::cout << v << std::endl;
}
};
// usage of A and B
A<int> a;
B b(10);
Question> In what circumstances, we have to provide template parameters in order to define a class variable.
For example,
If the class contains a template member variable or ???
Thank you
You have to provide template parameters to create an instance if the class is a class template. In your example,
class Ais a class template, andclass Bisn’t.Class template:
Not a class template:
In your example,
class Bhas a template constructor, and the argument can be used by the compiler to determine which specialization to make. So in this case, it generates a constructor equivalent tobecause the literal
10is anint. Constructors are not like functions, so this can only work if the compiler can figure out whatTis. See this related question for more details.