允许仅使用一组已定义的结构值

Allow to use only a defined set of structures values

我的 C++ 结构应该只包含有限的值。例如:

struct Foo {
  const int a;
  const char* const b;
  const bool c;
}

namespace allowed_values {
constexpr Foo first = {1, "asdf", true};
constexpr Foo second = {2, "fdsa", true};
constexpr Foo third = {3, "brrrr", false};
}

在 C++(最高 C++17)中是否有一些好的机制、设计模式或技巧允许我禁止使用非预期的其他值组合? IE。在不同的源文件中,它的行为如下:

// possible:
auto val1 = allowed_values::first;
// compilation error wanted:
Foo val2{4, "aaa", true};
// compilation error wanted (or at least nice-to-have):
constexpr Foo fourth = {4, "bbb", false};
auto val3 = fourth;

您可以将构造函数设为私有,这样就无法创建其他对象。您要创建的对象必须由朋友或 class 本身创建:

struct Foo {
  const int a;
  const char* const b;
  const bool c;
private:
    Foo(int a,const char* const b,bool c) : a(a),b(b),c(c) {}
public:
    static Foo first() { return {1, "asdf", true}; }
    static Foo second() { return {2, "fdsa", true};}
    static Foo third() { return {3, "brrrr", false};}
};