C++区分结构相同的类

pap*_*jam 1 c++ templates types

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

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

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";
}
Run Code Online (Sandbox Code Playgroud)

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

Aka*_*ksh 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.
Run Code Online (Sandbox Code Playgroud)

  • 使用类型而不是枚举可能更好,例如'struct fingers_tag','typedef NumberOfType <fingers_tag> NumberOfFinger'等等.这样您就不需要一个地方指定所有可能的类型变体. (3认同)