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++ 模板构造函数
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
