模板构造函数奇怪 [英] Template constructor weirdness
问题描述
后续问题,(我在编辑2中发现了这种情况)
following up on my previous question, (I found this situation in edit 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' ?
详细:对于模板构造函数,可以指定一个不是构造函数参数的模板参数当对象得到实例化时?
Detailed: For a template constructor, can you specify a template argument which is not part of the constructor's arguments when an object get's instantiated?
我认为这值得自己的问题。
I think this deserves a question of its own.
推荐答案
不,这是不可能的。
没有任何语法可以为构造函数模板提供显式模板参数。您只能为类模板作为整体提供显式模板参数。
There is no syntax with which you can provide explicit template parameters to a constructor template. You can only provide explicit template parameters for the class template as a whole.
[temp.arg.explicit]
(2003年的措辞,14.8.1 / 5)涵盖了这种情况。虽然该条款是非规范性的,但它向我们解释,作为语法的固有限制,这是不可能的:
The following text from [temp.arg.explicit]
(2003 wording, 14.8.1/5) covers the scenario. Though the clause is non-normative, it serves to explain to us that, as an inherent restriction of the grammar, this is not possible:
注意:因为显式模板
参数列表遵循函数
模板名称和因为转换
成员函数模板和
构造函数成员函数模板
被调用而不使用函数
name ,没有办法为
提供
显式模板参数列表这些函数模板。
Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates.
这部分是因为你从来没有实际调用构造函数。当你写,例如, A()
你不像一个函数调用构造函数,即使它看起来像你是(转换成员函数模板和构造函数成员函数调用模板而不使用函数名)。
This, partially, comes out of the fact that you never actually invoke the constructor explicitly yourself. When you write, say, A()
you are not calling the constructor like a function, even though it looks as if you are ("conversion member function templates and constructor member function templates are called without using a function name").
这篇关于模板构造函数奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!