If I have a simple structure like
struct Point { int x, y; };
then I can do
int main()
{
Point p1 = { 10 }; // x = 10, y = 0
Point p2 = { 10, 20 }; // x = 10, y = 20
Point p3 = { 10, 20, 30 }; // Compile error: too many initializers for ‘Point’
return 0;
}
I now want to have the same behaviour when initializing Point
with Point
becoming a class but with x
and y
becoming private and using accessors, etc.
My first attempt was
class Point
{
public:
Point( std::initializer_list<int> init )
{
switch( init.size() )
{
case 0: x = 0; y = 0; break;
case 1:
{
auto iter = init.begin();
x = *iter++; y = 0;
break;
}
case 2:
{
auto iter = init.begin();
x = *iter++; y = *iter++;
break;
}
default:
throw 0;
break;
}
}
private:
int x, y;
};
which kinda works but changes the compile time error into a runtime error. The question now is: How do I cause this class to behave the same as the simple struct, i.e. cause a compile time error when the initializer list is too large?
Looking around I found
- static_assert on initializer_list::size()
- Why is the size not a template argument of std::initializer_list?
Reading through the answers and comments I understand some of the constexpr
and static_assert
issues but am still no nearer to finding a solution to my question. Is it possible to cause a compile time error in C++11 (or C++14)? The compiler definitely knows all it needs to and it seems a likely enough thing for someone to want to do that the standard would have rolled it in somehow.