1

是否可以启用、禁用类成员函数?

情况:我有一堂有两种类型的课。每个类型都有自己的构造函数。一种类型需要一个不能具有另一种类型的功能。

例子:

class A {
    enum struct TypeEnum : int {
        TYPE_1 = 1,
        TYPE_2 = 2
    };
    const TypeEnum type;

    int x;


    A(void) : type(TypeEnum::TYPE_1) { }
    A(int _x) : type(TypeEnum::TYPE_2) { 
        x = _x;
    }


    // function only for Type 2
    void A::operator += (const int& n) {
        x = x + n;
    }
};

int main() {
    A test1 = new A();
    A test2 = new A(1);

    test1 += 5;  // compiler error should be here
    test2 += 5;  // OK

    return 0;
}

有可能是这样的:

class A {
    enum struct TypeEnum : int {
        TYPE_1 = 1,
        TYPE_2 = 2
    };
    const TypeEnum type;

    int x;


    A(void) : type(TypeEnum::TYPE_1) { }
    A(int _x) : type(TypeEnum::TYPE_2) { 
        x = _x;
    }


    // Is somethig like this realy impossible
    void A::operator += (const int& n) -> enable_if(type == TypeEnum::Type2) { // if not compile error
        x = x + n;
    }
};
4

3 回答 3

3

您可以使用专业化:

enum struct TypeEnum : int {
    TYPE_1 = 1,
    TYPE_2 = 2
};

template<TypeEnum Type>
class A;

template<>
class A<TypeEnum::TYPE_1>
{
public:
    A(void) { }
};

template<>
class A<TypeEnum::TYPE_2>
{
public:
    A(int _x) { 
        x = _x;
    }
    int x;
    void operator += (const int& n) {
        x = x + n;
    }
};

int main() {
    A<TypeEnum::TYPE_1> test1;
    A<TypeEnum::TYPE_2> test2{1};

    test1 += 5;  // compiler error should be here
    test2 += 5;  // OK

    return 0;
}
于 2014-02-08T16:25:12.387 回答
1

也许以下可能会有所帮助:

class A {
public:
    explicit A(TypeEnum type) : type(type) {}
    virtual ~A() {}
protected:
    enum struct TypeEnum : int {
        TYPE_1 = 1,
        TYPE_2 = 2
    };
    const TypeEnum type;
};

class B : public A{
public:
    B() : A(TYPE_1) {}
};

class C : public A{
public:
    explicit C(int x) : A(TYPE_2), x(x) {}
    C& operator += (int n) { x = x + n; }
private:
    int x;
};

继承在这里是为了用一个通用类型来反映你的情况。其他不需要。

无论如何你都可以做的事情:

B make_A() { return B{}; }
C make_A(int x) { return C{x}; }

int main() {
    auto test1 = make_A();  // B
    auto test2 = make_A(1); // C

    test1 += 5;  // compiler error should be here
    test2 += 5;  // OK

    return 0;
}
于 2014-02-08T16:21:20.333 回答
0

奇怪的是你在这里没有得到编译错误:

// function only for Type 2
void A::operator += (const int& n) {
    x = x + n;
}

我以为你想要这样的东西:

// function only for Type 2
A& operator += (int n) {
    x = x + n;
    return *this;
}

回答你的问题 - C++ 不是这样工作的。尽管如此,您可以使用模板实现类似的东西,但我建议不要这样做,除非它只是一个测试程序。

于 2014-02-08T16:06:06.283 回答