Shane Hou
Shane Hou

Reputation: 5028

Issue with calling a method from template class

I have a template class method like that:

template<class T>
static tmpClass<T>* MakeInstance(T value)
{

  tmpClass<T> *pointer = new tmpClass<T>(value);

  return pointer;
}

And I used various ways to call this method:

Way 1:

MakeInstance<int>(val); // This is OK.

Way 2:

MakeInstance(int val); // ERROR: Expected '(' for function-style cast or type construction

Way 3:

MakeInstance(int (val)); // This is also OK.

Way 4:

MakeInstance(int, (val)); // The same issue with way 2

Way 5:

MakeInstance((int), (val)); // ERROR: Expect expression with ","

Way 6:

MakeInstance((int) val); // This is also OK.

Way 7:

MakeInstance<int val>; // ERROR: Expected ">"

So is there any difference between way 1,3,6? Why we can't use "," to split "T" and "value", just because we have to follow the template strictly? But why we can also have "T" in "<>"?

Upvotes: 0

Views: 890

Answers (1)

Alok Save
Alok Save

Reputation: 206566

In #1 you explicitly specify you want to call the template function with specified type.

In #3 & #6 the function to be called is determined by function template argument deduction. The casting tells the compiler to look for a function which takes an int since compiler cannot find it uses the template function to generate one.

Note that the c-style casts:

T(val);

and

val(T);

both are identical and mean the same.

Upvotes: 1

Related Questions