可能重复:
Can the template parameters of a constructor be explicitly specified?模板的构造函数的怪事
我以前question跟进,(我发现这个情况,编辑2)
特出简单的代码:
#include <iostream>
struct Printer
{
Printer() { std::cout << "secret code" << std::endl; }
};
template <class A>
struct Class
{
template <class B, class C>
Class(B arg)
{
C c; /* the 'secret code' should come from here */
std::cout << arg << std::endl;
}
Class(double arg) { std::cout << "double" << std::endl; }
Class(float arg) { std::cout << "float" << std::endl; }
/* this forbids the use of printer in the first parameter */
Class(Printer printer) { throw std::exception(); /* here be dragons */ }
};
int main()
{
Class<int> c(1.0f);
Class<int>* ptr = new Class<int>((double)2.0f);
return 0;
}
// Can anyone print 'secret code' while creating an object of type 'Class' ?
详细说明:对于模板构造函数,您可以在对象被实例化时指定一个不属于构造函数参数一部分的模板参数吗?
我认为这是值得一个问题。
这样的事情的语法必须看起来像'类 objectA (initB);',我不认为这是允许的(我会让别人引用章节和诗句,我不会没有标准记忆)。至少,如果可能的话,你可能必须声明模板构造函数为'explicit',因为当隐式构造一个临时变量时无法确定'C'。真正的问题是:为什么你需要做这样的事情,特质课是否会解决你的问题,如果不是,为什么不呢? – 2011-06-15 14:07:33
目前它只是一个编程好奇心 – 2011-06-15 14:10:55