c++ - 特定数据类型的模板类

标签 c++ class oop templates

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

error C2976: 'Test': too few template arguments

note: see declaration of 'Test'

error C2244: 'Test::Output': unable to match function definition to an existing declaration

error C2662: 'void Test::Output(void)': cannot convert 'this' pointer from 'Test' to 'Test &'

error C2514: 'Test': class has no constructors

#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;
}

最佳答案

类模板不能重载(函数模板可以),只能特化。如果你想要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

编辑

Can I set the second template as a specific data type (such as std::string)? and use Test like Test<int, std::string>

是的。例如

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

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

LIVE

关于c++ - 特定数据类型的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53022246/

相关文章:

c++ - 多线程同步

php - 使用 PHP OOP 管理数据库

java - 遍历 Java 中的链表?

c++ - 具有不同成员变量的多个 Action 的通用类

c++ - 如何获取 const* char 参数的键盘输入?

c++ - unique_ptr 不调用析构函数来释放指针

c++ - 如何使用区分大小写的元素对 std::list 进行排序?

javascript - 如何在 Javascript 类内部创建类

c# - 如何枚举直接在继承类上定义的接口(interface)列表?

c# - Head First C# 练习