我有以下模板函数:
template<typename T>
T test_function(T arg) {return arg;}
我可以用为整数创建一个专门的版本
template<>
int test_function(int arg) {return arg;}
如果我经常将这个函数与整数一起使用,这是实用的。所以我可以称之为:
test_function(some_integer); // easy!
test_function<int>(some_integer); // not necessary all the time.
现在我有以下课程:
template<typename T>
class Foo
{
public:
Foo();
};
我想能够称之为:
Foo foo1; // how do I do this?
Foo<int> foo2; // I don't want to use this all the time.
我如何定义这个类,以便能够在不使用尖括号的情况下创建它的实例?我想应该不太难,但到目前为止我还想不通。。。
您应该使用默认参数(int),然后:
template<typename T = int> class Foo {};
Foo<> foo2;
或者创建一个别名:
using MyFoo = Foo<int>; //or just Foo<> if using default argument
MyFoo foo1;
我相信,即使所有模板参数都有默认值,也不能在创建模板类的对象时不表明它是模板类。
注意:using
是C++11关键字,对于遗留代码/编译器使用typedef
。
template<typename T>
T test_function(T arg) {return arg;}
template<>
int test_function<int>(int arg) {return arg;}