将类模板推迟到其构造函数
Postpone class template to its constructor
恐怕我正在寻找的东西是不可能的。它可能需要更改我的设计。我正在寻找将类模板推迟到其构造函数。下面是示例:
以下代码工作没有问题:
#include <iostream>
using namespace std;
template<class T1,class T2>
T1 product(T1 t1,T2 t2)
{
return (T1)(t1*t2);
}
int main()
{
double t1=5.5;
int t2=4;
cout<<t1<<" x "<<t2<<" = "<<product(t1,t2)<<endl;
return 0;
}
现在,如果我想将函数product
包装在类中:
#include <iostream>
using namespace std;
template<class T1,class T2>
class A
{
public:
T1 num1;
T2 num2;
template<class T1,class T2>
A(T1 t1,T2 t2)
{
num1=t1;
num2=t2;
}
T1 product()
{
return (T1)(num1*num2);
}
T1 division()
{
return (T1)(num1/num2);
}
};
int main()
{
double t1=5.5;
int t2=4;
// i need types here, this will not compile because
// i would need to explicitly state A<double, int> here.
class A a(t1,t2);
cout<<t1<<" x "<<t2<<" = "<<a.product(t1,t2)<<endl;
return 0;
}
此代码无法编译。显然是因为它正在寻找<double,int>
作为类的模板。修复编译器错误很容易,不是我关心的问题。
担心的是,现在,我觉得我失去了优势!在以前的代码中,我可以调用该函数而不用担心类型。我为函数提供了参数。现在我必须首先为类提供参数类型。我无法从 t1 和 t2 的自动检测类型定义一个类。有没有办法将类模板推迟到其构造函数?
也许您认为为类模板提供类型非常容易,不值得争论!但是想象一下一个非常复杂的案例。
你创建了一个返回"正确的事物(tm)"的创建者函数:
template<typename T1, typename T2>
auto make_A(T1 n1, T2 n2)->A<T1, T2> {
return A<T1, T2>(n1, n2);
}
稍后像这样使用它:
auto a = make_A(t1, t2);
仅此而已。但请注意:auto
是一个非常"新"的关键字,但如果您遇到旧的编译器,您可能会遇到麻烦。在重构你的大型项目之前,你应该检查你必须支持的最低编译器。
更多信息:
- 斯科特·迈耶斯(Scott Meyers)的《类型演绎和你为什么在乎》https://www.youtube.com/watch?v=wQxj20X-tIU
- 迈克行动"面向数据的设计和C++"https://www.youtube.com/watch?v=rX0ItVEVjHc ...这个演讲是质疑你对"上课因为为什么不上课"的需求?!
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为