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

C++ created multiple struct with class template

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

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

您可以为此结合使用继承和模板。
按照您的思路,可能的代码是:

template <class T> struct X {
    int time = 10;
    virtual void doStuff(const T&) = 0;
    virtual T getStuff() = 0;
};

struct A : X<A>
{
    void doStuff(const A& a) {
        cout << "Do A stuff" << endl;
    }

    A getStuff() {
        return *this;
    }
};

struct B : X<B>
{
    void doStuff(const B& value) {
        cout << "Do B stuff" << endl;
    }

    B getStuff() {
        return *this;
    }
};

然后,测试我们有:

int main()
{
    A a; B b;

    a.doStuff(a);  // Ok
    b.doStuff(b);  // Ok
    a.doStuff(b);  // fail
    b.doStuff(a);  // fail
    b = b.getStuff();  // Ok
    b = a.getStuff();  // fail

    return 0;
}