C++ 使用类模板创建多个结构

标签 c++ template-specialization template-classes

我想创建基本相同但类型不同的类型安全结构,因此它们需要不同的函数签名。

struct A {
    Time t;
    void doStuff(const A&);
    A getStuff();
};

struct B {
    Time t;
    void doStuff(const B&);
    B getStuff();
};

如果我为类(class)起诉一个模板

template<class T>
struct X {
    Time t;
    void doStuff(const X&);
    X getStuff();
};

如何使函数类型安全并为类型 A 的结构 X 和类型 B 的结构 X 定义不同的函数签名?

最佳答案

尝试添加一些未使用的模板参数。

template <int>
struct X{
    Time t;
    void doStuff(const X&); // You missed return type
    X getStuff();
}; // You missed a semicolon

// Great thanks to "aschepler"

现在您可以(C++11 语法)

using A = X<1>;
using B = X<2>;
// typedef X<1> A;
// typedef X<2> B;

下面的代码会失败,这正是你想要的:

A a; B b;
a.doStuff(b); // Fail
a = b.getStuff(); // Fail

关于C++ 使用类模板创建多个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46576447/

相关文章:

c++ - 将 const void* 转换为 const int*

c++ - 将 shared_ptr 与多继承类一起使用

c++ - 适用于 C++ 的良好 Windows 注册表包装器

c++ - 指针和 C 风格数组变量的专用模板

c++ - 为什么使用范围解析运算符会更改调用全局命名空间中的哪个重载模板?

c++ - 将模板类从 C++ 库导出到 VB.NET 和 C#

c++ - 模板 : one for string and one for anything else 中的不同构造函数

c++ - g++ 和 clang++ 在 `std::make_index_sequence` 和 `std::index_sequence` 用于模板参数默认类型时的不同行为

c++ - 特化一个模板类?

c++ - 如何动态转换模板类