我有这个最小的,人为的C++代码示例,带有一个默认类型参数的模板结构:
#include <iostream>
using namespace std;
template <class T=int>
struct AddsFourtyTwo {
template <class U>
static U do_it(U u) {
return u + static_cast<T>(42);
}
};
int main() {
double d = 1.24;
std::cout << AddsFourtyTwo::do_it(d) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译此代码时,我在g ++ 4.9.1中收到以下错误:
$ g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:14:18: error: 'template<class T> struct AddsFourtyTwo' used without template parameters
std::cout << AddsFourtyTwo::do_it(d) << std::endl;
^
Run Code Online (Sandbox Code Playgroud)
如果我为T指定int,那么它编译并产生预期的输出(43.24).我的问题是,为什么这有必要呢?如果您需要指定类型,默认类型参数在AddsFourtyTwo的定义中会做什么?
您不需要指定类型,但语言不允许使用模板作为实际类型而不指定某个参数列表:
std::cout << AddsFourtyTwo<>::do_it(d) << std::endl;
Run Code Online (Sandbox Code Playgroud)