C++ template constructor(C++ 模板构造函数)
问题描述
我希望有一个带有不带参数的模板构造函数的非模板类.
I wish to have a non-template class with a template constructor with no arguments.
据我所知,这是不可能的(因为它会与默认构造函数冲突 - 我说得对吗?),解决方法如下:
As far as I understand, it's impossible to have it (because it would conflict with the default constructor - am I right?), and the workaround is the following:
class A{
template <typename U> A(U* dummy) {
// Do something
}
};
也许有更好的替代方案(或更好的解决方法)?
Maybe there is a better alternative for this (or a better workaround)?
推荐答案
在调用构造函数模板时无法明确指定模板参数,因此必须通过参数推导来推导.这是因为如果你说:
There is no way to explicitly specify the template arguments when calling a constructor template, so they have to be deduced through argument deduction. This is because if you say:
Foo<int> f = Foo<int>();
是类型 Foo
的模板参数列表,而不是它的构造函数.构造函数模板的参数列表无处可去.
The <int>
is the template argument list for the type Foo
, not for its constructor. There's nowhere for the constructor template's argument list to go.
即使使用您的解决方法,您仍然必须传递参数才能调用该构造函数模板.根本不清楚您要实现的目标.
Even with your workaround you still have to pass an argument in order to call that constructor template. It's not at all clear what you are trying to achieve.
这篇关于C++ 模板构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 模板构造函数


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05