constexpr变量的继承和设置

问题描述 投票:0回答:1

我正试图实现以下行为。

我有两个类,继承自同一个类。它们都会执行一些工作,在某个时刻改变它们的状态,在某个时刻,这个状态需要被检查。检查的方法很相似,对于两个类来说,在两个测试中,我们都会将实际状态和期望状态进行比较。唯一不同的是期望状态,它是依赖于类的。

在代码中,一个最小的例子,我是这样实现的。

#include <iostream>

class A {
public:
    static int x = 1;
    int y;
    A(int _y): y(_y) {}

    void test() {
        bool passed = x == y;
        std::cout << "Test" << (passed ? "" : " not") << " passed\n";
    }
};

class B : public A {
public:
    B(int _y): A(_y)
    {
        x = 2; 
    }
};

class C : public A {
public:
    C(int _y) : A(_y)
    {
        x = 3;
    }
};

int main()
{
    B b(2);
    b.test(); // Test passed

    C c(2);
    c.test(); // Test not passed
    return 0;
}

所以一个B的实例通过了测试,如果值是 y2的实例,而 C 如果该值是 3. 然而,我不喜欢这种实现方式,因为它的值是 x 可以改变--即使 x 是私有的,一个朋友类仍然可以修改它。理想的情况是,我希望定义一个名为 x 作为 const的传递值,并作为 BC 是事先知道的(在编译时),甚至可能是 constexpr.

我的问题如下。

是否可以用const或constexpr的值来实现上述行为?x? 价值可以 x 为每个继承类设置,但仍在基类中测试?

c++ inheritance c++17 constexpr
1个回答
2
投票

模板似乎有帮助,尤其是继承似乎只是为了简化代码而来。

template <int x>
class A {
public:
    int y;
    A(int _y): y(_y) {}

    void test() {
        bool passed = x == y;
        std::cout << "Test" << (passed ? "" : " not") << " passed\n";
    }
};

// using B = A<2>; // Seems even enough in your example
class B : public A<2> {
public:
    using A<2>::A;
};

class C : public A<3> {
public:
    using A<3>::A;
};
© www.soinside.com 2019 - 2024. All rights reserved.