C ++没有模板参数的专用类构造函数(跳过尖括号)

时间:2016-04-08 06:45:42

标签: c++ templates template-specialization

我有以下模板功能:

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.

如何定义此类以便能够在不使用尖括号的情况下创建它的实例?我想不应该太难,但到目前为止我无法弄明白......

2 个答案:

答案 0 :(得分:2)

您应该使用默认参数(int),然后使用:

packages: 
  yum:
    libjpeg-turbo-devel: []

或制作别名:

template<typename T = int> class Foo {};
Foo<> foo2;

我相信即使所有模板参数都有默认值,你也不能创建一个模板化类的对象而不指示它是一个模板类。

注意:using MyFoo = Foo<int>; //or just Foo<> if using default argument MyFoo foo1; 是C ++ 11关键字,对遗留代码/编译器使用using

答案 1 :(得分:0)

template<typename T>
T test_function(T arg) {return arg;}

template<>
int test_function<int>(int arg) {return arg;}