1
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

q0987
  • 34,938
  • 69
  • 242
  • 387

1 Answers1

3

You have to provide template parameters to create an instance if the class is a class template. In your example, class A is a class template, and class B isn't.

Class template:

template <typename T> class A {};

Not a class template:

class B { 
  // code may include function template, etc.
  // but the class itself is not a class template
};

In your example, class B has 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 to

B(const int&);

because the literal 10 is an int. Constructors are not like functions, so this can only work if the compiler can figure out what T is. See this related question for more details.

Community
  • 1
  • 1
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • +1 for putting it together in better words than i could.You could also add a detail as to why it is not necessary for specifying a type while creating the object in second case, eventhough the constructor is a template function.I see the Q now and I think that was the purpose of the Q. – Alok Save May 31 '12 at 16:18
  • @Als I tried to explain the latter point in an edit. It is complicated, because one cannot tell the compiler what T is in the case of a constructor... – juanchopanza May 31 '12 at 16:29
  • Exactly and that is what the OP seems to be after. I realized it pretty much after i posted but saw your answer was much better than mine and could be even better if explained that detail.Just that, you already have my +1. :) – Alok Save May 31 '12 at 16:32
  • I'd say that `class A` is a class template. `A` is not a class, so it's somewhat misleading to call it a template class. – Steve Jessop May 31 '12 at 16:37
  • @SteveJessop thanks, I agree entirely. I realise both terms are used, but `class template` is more accurate. – juanchopanza May 31 '12 at 17:25