我有一个最小的,人为设计的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;
}
当我尝试编译此代码时,使用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;
^
如果我为T指定int,则它将编译并产生预期的输出(43.24)。我的问题是,为什么要这样做?如果仍然需要指定类型,则默认类型参数在AddsFourtyTwo的定义中起什么作用?
你并不需要指定类型,但使用模板作为实际类型的语言不允许没有指定一些参数列表:
std::cout << AddsFourtyTwo<>::do_it(d) << std::endl;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句