恐怕我要找的是不可能的。它可能需要改变我的设计。我正在寻找将类模板推迟到其构造函数。这是示例:
下面的代码没有问题:
#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
是一个非常"new"的关键字,如果您遇到旧的编译器,您可能会遇到麻烦。在重构您的大型项目之前,您应该检查您必须支持的最低编译器。
更多信息:
- Scott Meyers“类型推导和您关心的原因”https://www.youtube.com/watch?v=wQxj20X-tIU
- Mike Action“面向数据的设计和 C++”https://www.youtube.com/watch?v=rX0ItVEVjHc ......这个演讲是为了质疑你对“为什么不上课?!”的需求
关于c++ - 将类模板推迟到其构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28019156/