0

我有一个这样的模板类方法:

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

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

  return pointer;
}

我使用了各种方法来调用这个方法:

方式一:

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

方式二:

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

方式3:

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

方式四:

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

方式5:

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

方式6:

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

方式7:

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

那么方式1、3、6有什么区别吗?为什么我们不能用“,”来分割“T”和“值”,仅仅因为我们必须严格遵循模板?但是为什么“<>”中也可以有“T”呢?

4

1 回答 1

1

#1明确指定要调用具有指定类型的模板函数时。

#3&#6中,要调用的函数由函数模板参数推导确定。转换告诉编译器寻找一个函数,该函数需要一个,int因为编译器找不到它使用模板函数来生成一个。

请注意,c 风格的演员表:

T(val);

val(T);

两者都是相同的并且意思相同。

于 2012-06-18T04:50:31.130 回答