特定数据类型的模板类

时间:2018-10-27 13:16:02

标签: c++ class oop templates

(为简单起见,对代码进行了简化) 我想创建一个带有模板E A的Test类,以及一个只带有E模板的Test类。完成此操作并尝试编译我的代码时,出现以下错误:

  

错误C2976:“测试”:模板参数过多

     

注意:请参见“测试”的声明

     

错误C2244:“ Test :: Output”:无法将函数定义与   现有声明

     

错误C2662:“无效测试::输出(无效)”:无法转换“此”   从“测试”到“测试&”的指针

     

错误C2514:“测试”:类没有构造函数

#include <iostream>
#include <string>
template <typename E, typename A>
class Test
{
public:
    Test(E *e = nullptr, A *a = nullptr) : a(e), b(a) {}
    void Output();

private:
    E * a;
    A *b;
};
template <typename E, typename A>
void Test<E, A>::Output()
{
    std::cout << " " << *a << " " << *b;
}

template <typename E>
class Test
{
public:
    Test(E *e = nullptr, std::string *a = nullptr) : a(e), b(a) {}
    void Output();

private:
    E * a;
    std::string *b;
};

template<typename E>
void Test<E>::Output()
{
    std::cout << *a << *b;
}
int main()
{
    int a = 10;
    std::string str = "hi";

    Test<int> t(&a, &str);
    t.Output();
    return 0;
}

2 个答案:

答案 0 :(得分:3)

类模板不能重载(功能模板可以重载),而只能是专门的。如果您想要partial specialization,应该是

template <typename E>
class Test<E, E>
{
    ...
};

template<typename E>
void Test<E, E>::Output()
{
    ...
}

使用它时,应始终指定两个模板参数作为要声明的主要模板。即

Test<int, int> t(&a, &str); // the partial specialization will be used

编辑

  

我可以将第二个模板设置为特定的数据类型(例如std::string)吗?并像Test一样使用Test<int, std::string>

是的。例如

template <typename E>
class Test<E, std::string>
{
    ...
};

template<typename E>
void Test<E, std::string>::Output()
{
    ...
}

LIVE

答案 1 :(得分:0)

不幸的是,您不能通过声明template typename E> class Test来“重载”类模板。类Test必须带有两个模板参数。

这里的解决方案是声明一个完全不同的模板类或使第二个模板参数为可选并编写模板特化:

class Dummy;
template <typename E, typename A = Dummy>
class Test
…

template <typename E>
class Test<E, Dummy>

因此语法Test<int> t(&a, &str);仍然有效。