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

C++ C++;使用类模板创建了多个结构,c++,template-specialization,template-classes,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(); }; 如果我为该类使用模板 template<class T> struct X { Time t;

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

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

struct B {
    Time t;
    void doStuff(const B&);
    B getStuff();
};
如果我为该类使用模板

template<class T>
struct X {
    Time t;
    void doStuff(const X&);
    X getStuff();
};
模板
结构X{
时间t;
无效浓度凝灰岩(常数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"

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

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

你的模板看起来不对。你应该写
doStuff(constx&)
X getStuff()。谢谢。编辑的问题另一个bug:
doStuff()
的返回类型是什么?根本不清楚你在问什么。您的代码几乎是有效的(除了前面提到的缺少的返回类型和一些缺少的分号)。您希望如何使用类型和/或模板,或者您希望添加或更改哪些尚未显示的类型和/或模板?@aschepler我认为这已经足够清楚了。OP多次提到“类型安全”,让我试试。好奇,我需要第二个模板做什么?好的,谢谢,期待着稍后尝试。模板定义忽略任何或所有模板参数是完全合法的。(事实上,在这种情况下,您甚至可以省略参数名,如
template struct X{
..)干得好,@aschepler。现在它是真正的类型安全了。@aschepler现在我如何定义函数?
template void X::doStuff()
看起来不太好。
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;
}