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++ 模板构造函数
基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
