带有方法和静态实例的C ++ 11枚举的成语?

史蒂夫·埃默森

我想执行以下操作(无法编译):

class Foo {
    int value;

    Foo(const int arg)
        : value{arg}
    {}

public:    
    static const Foo a{0};
    static const Foo b{1};
    static const Foo c{2};

    Foo func(const Foo& foo) {...}
};

这样就Foo可以严格控制的实例(如中的enum),这样我就可以编写类似auto foo = Foo::a;和的代码auto foo = Foo::a.func(Foo::b);

不幸的是,由于静态实例的类型不完整,因此代码无法在C ++ 11下编译。

有这个成语吗?

扬·舒尔特克

您可以很容易地做到这一点,但需要将常量的定义放在类之外:

class Foo {
    int value;

    // In C++17, you could make this constexpr.
    Foo(const int arg)
        : value{arg}
    {}

public:
    // in C++20, you could make these constinit.
    static const Foo a;
    static const Foo b;
    static const Foo c;
};

// In C++11 these need to go in the source file to avoid linker errors.
// In C++17 you could make them inline and put them in the header.
// In C++20 you could make them constinit.
const Foo Foo::a = 0;
const Foo Foo::b = 1;
const Foo Foo::c = 2;

我不会将其称为一种优雅的解决方案。特别是在C ++ 11中,编译器无法内联这些常量,因为它们需要进入源文件。这会对性能产生重大影响。因此,如果您要这样做,我建议至少使用C ++ 17,如果不是C ++ 20,则建议使用。

通常,C ++枚举应为整数常量,并且不支持获取enumJava中类似的序数或名称一种替代方法是使用不enum class带任何值的(默认值为0、1、2,...),然后将它们用作查找表中的索引。

使用switchfor属性也可以达到目的:

enum class Axis : unsigned { X, Y, Z };

// in C++17, you could make this constexpr.
inline const char *nameOf(Axis axis)
{
    switch (axis) {
    case Axis::X: return "X";
    case Axis::Y: return "Y";
    case Axis::Z: return "Z";
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章