可能重复:
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' ?
详细说明:对于模板构造函数,是否可以指定一个模板参数,该参数在实例化对象时不是构造函数参数的一部分?
我认为这应该是一个自己的问题。
答案 0 :(得分:3)
不,这是不可能的。
没有语法可以为构造函数模板提供显式模板参数。您只能为类模板提供显式模板参数。
[temp.arg.explicit]
(2003年措辞,14.8.1 / 5)的以下文字涵盖了该情景。虽然该条款是非规范性的,但它可以向我们解释,作为语法的固有限制,这是不可能的:
注意:因为显式模板 参数列表跟随函数 模板名称和因为转换 成员函数模板和 构造函数成员函数模板 在不使用函数的情况下调用 名称,没有办法提供 显式模板参数列表 这些功能模板。
部分原因是你自己从未真正明确地调用构造函数。当你编写时,A()
你没有像函数一样调用构造函数,即使它看起来像你是(“转换成员函数模板和构造函数成员函数模板在不使用函数名称的情况下被调用”)。
答案 1 :(得分:0)
我想他想知道如何使用C作为SomeType来实例化这个类:
template<typename A>
class foo
{
template<typename B, typename C>
foo(B b)
{
C c;
}
};
我不知道这是否可行。