c++区分结构相同的类

C++ distinguishing structurally identical classes

本文关键字:结构 c++      更新时间:2023-10-16

我有几个类型共享相同的行为,具有相同的构造函数和操作符。有些像这样:

class NumberOfFingers
{
public:
    void operator=(int t) { this->value = t; }
    operator int() const { return this->value; }
private:
    int value;
};

NumberOfToes是相同的。

每个类都有不同的行为,下面是一个例子:

std::ostream& operator<<(std::ostream &s, const NumberOfFingers &fingers)
{
    s << fingers << " fingersn";
}
std::ostream& operator<<(std::ostream &s, const NumberOfFingers &toes)
{
    s << toes << " toesn";
}

我怎样才能最小化类定义中的重复,同时保持类类型的不同?我不想让NumberOfFingersNumberOfToes从一个共同的基类派生,因为我失去了构造函数和操作符。我想一个好的答案应该与模板有关。

是的,你是正确的,因为它将涉及模板:)

enum {FINGERS, TOES...};
...
template<unsigned Type> //maybe template<enum Type> but I havent compiled this.
class NumberOfType
{
public:
    void operator=(int t) { this->value = t; }
    operator int() const { return this->value; }
private:
    int value;
};
...
typedef NumberOfType<FINGERS> NumberOfFinger
typedef NumberOfType<TOES> NumberOfToes
... so on and so forth.