首页 > 解决方案 > 特定数据类型的模板类

问题描述

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

错误 C2976:“测试”:模板参数太少

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

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

错误 C2662:“void Test::Output(void)”:无法将“this”指针从“Test”转换为“Test &”

错误 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;
}

标签: c++classooptemplates

解决方案


类模板不能重载(函数模板可以),而只能是特化的。如果你想要部分专业化,它应该是

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

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

并且在使用它时,您应该始终指定两个模板参数作为被声明的主模板。IE

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()
{
    ...
}

居住


推荐阅读