0

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 "<>"?

Shane Hou
  • 4,808
  • 9
  • 35
  • 50
  • 3
    You should read a [good book](http://stackoverflow.com/q/388242/21475) on templates. It seems you're not clear on the basic syntax yet. – Cameron Jun 18 '12 at 04:49
  • 1
    What is the type of `val` ? If it's `int` then you may not need 1,3,6. Simply call as `MakeInstance(val);`. – iammilind Jun 18 '12 at 04:51
  • @iammilind it has various types like int, short, long, char, string... I think you are talking about the default type in template. – Shane Hou Jun 18 '12 at 05:03

1 Answers1

1

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533