bar*_*rej 4 c++ templates c++11
我担心我所寻找的是不可能的.它可能需要改变我的设计.我正在寻找将类模板推迟到其构造函数.这是一个例子:
以下代码没有问题:
#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;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我想将函数包装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;
}
Run Code Online (Sandbox Code Playgroud)
此代码无法编译.显然是因为它正在寻找<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);
}
Run Code Online (Sandbox Code Playgroud)
并在以后使用它:
auto a = make_A(t1, t2);
Run Code Online (Sandbox Code Playgroud)
就是这样.但要注意:这auto是一个非常"新的"关键字,如果遇到旧编译器,可能会遇到麻烦.在重构您的庞大项目之前,您应该检查您必须支持的最低编译器.
更多的信息:
| 归档时间: |
|
| 查看次数: |
200 次 |
| 最近记录: |