将类模板推迟到其构造函数

Postpone class template to its constructor

本文关键字:迟到 构造函数 推迟      更新时间:2023-10-16

恐怕我正在寻找的东西是不可能的。它可能需要更改我的设计。我正在寻找将类模板推迟到其构造函数。下面是示例:

以下代码工作没有问题:

#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 ...这个演讲是质疑你对"上课因为为什么不上课"的需求?!