C ++区分结构相同的类

时间:2011-10-20 08:50:30

标签: c++ templates types

我有几种类型,它们具有共同的行为,并且具有相同的构造函数和运算符。有些看起来像这样:

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 << " fingers\n";
}

std::ostream& operator<<(std::ostream &s, const NumberOfFingers &toes)
{
    s << toes << " toes\n";
}

如何最大限度地减少类定义中的重复,同时保持类型不同?我不希望NumberOfFingersNumberOfToes派生自一个公共基类,因为我丢失了构造函数和运算符。我猜一个好的答案会涉及模板。

1 个答案:

答案 0 :(得分:5)

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

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.
相关问题