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

标签 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;
}

现在,如果我想包装函数 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"的关键字,如果您遇到旧的编译器,您可能会遇到麻烦。在重构您的大型项目之前,您应该检查您必须支持的最低编译器。

更多信息:

关于c++ - 将类模板推迟到其构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28019156/

相关文章:

c++ - 如何检测类型是否具有运算符 << 重载?

c++ - 非内置函数的模板,内置函数的重载

c++ - std::atomic 的默认值是多少?

sockets - 在ASIO Reactor中使用Lambda的Auto vs Typedef

c++ - 无法写入/proc/<pid>/coredump_filter

c++ - GLFW GLAD 纹理未绘制,黑色正方形

C++ 添加 2 个 3D vector 返回垃圾值

c++ - Visual Studio 2012 中的单元测试 C++ 控制台应用程序

c++ - 调用模板和特化来交叉验证结果?

c++ - 多字节字符 '\377777' 是如何工作的?