Reputation: 458
I have C++ structure which should contain only a limited of values. For example:
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};
}
Is there some nice mechanism, design pattern or a trick in C++ (up to C++17), which allows me to forbid using other values combinations than intended? I.e. in a different source file it behaves as follows:
// 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;
Upvotes: 0
Views: 101
Reputation: 123084
You can make the constructor private, so no other objects can be created. The objects you want to create must then be created by a friend or the class itself:
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};}
};
Upvotes: 3