没有模板参数的类的C++专用构造函数(跳过尖括号)
C++ Specialized constructor of class without template arguments (skip angle brackets)
我有以下模板函数:
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;}
相关文章:
- 具有专用化的模板类中的可靠条件复制和移动构造函数
- 构造函数 (g++) 的显式模板专用化
- 构造函数的部分模板专用化
- 如何在另一个类模板中定义完全专用类的构造函数
- 模板专用类之间的构造函数重载
- 使用模板的构造函数专用化
- 如何将模板构造函数专用化移动到 cpp 文件
- 模板类模板构造函数专用化
- 定义专用模板类构造函数时避免重复
- 模板化类的模板化构造函数的显式模板专用化
- 具有 n 个参数的模板专用构造函数
- 不会调用模板化构造函数的专用模板
- 没有模板参数的类的C++专用构造函数(跳过尖括号)
- 专用于非模板类的模板化构造函数
- 专用于模板类构造函数
- C++单个构造函数模板专用化
- 模板专用化没有匹配的构造函数
- 在模板专用化中添加单个构造函数方法
- 从派生类实现基类构造函数专用化的替代方法是什么
- 类定义中构造函数的模板专用化