模板构造函数的怪异
Template constructor weirdness
本文关键字:构造函数 更新时间:2023-10-16
可能重复:
构造函数的模板参数可以显式指定吗?
继我之前的问题之后,(我在编辑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' ?
详细说明:对于模板构造函数,当对象被实例化时,你能指定一个不属于构造函数参数的模板参数吗?
我认为这应该有一个自己的问题。
不,这是不可能的。
没有语法可以为构造函数模板提供显式模板参数。只能为整个类模板提供显式模板参数。
[temp.arg.explicit]
的以下文本(2003年措辞,14.8.1/5)涵盖了该场景。尽管该条款是非规范性的,但它可以向我们解释,作为语法的固有限制,这是不可能的:
注意:因为显式模板函数后面的参数列表模板名称,以及,因为转换成员函数模板和构造函数成员函数模板在不使用函数的情况下调用name,无法提供的显式模板参数列表这些函数模板。
这在一定程度上源于这样一个事实,即您从未亲自显式调用构造函数。例如,当您编写A()
时,您并不是像函数一样调用构造函数,即使它看起来像是("在不使用函数名的情况下调用转换成员函数模板和构造函数成员函数模板")。
我想他想知道如何用C将这个类实例化为SomeType:
template<typename A>
class foo
{
template<typename B, typename C>
foo(B b)
{
C c;
}
};
我不知道这是否可能。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为