It would be useful to have 'constexpr' parameters in order to distinguish compiler-known values and so be able to detect errors at compile time. Examples:
int do_something(constexpr int x)
{
static_assert(x > 0, "x must be > 0");
return x + 5;
}
int do_something(int x)
{
if(x > 0) { cout << "x must be > 0" << endl; exit(-1); }
return x + 5;
}
int var;
do_something(9); //instance 'do_something(constexpr int x)' and check arg validity at compile time
do_something(0); //produces compiler error
do_something(var); //instance 'do_something(int x)'
This is invalid code for now. Can somebody explain to me why this can't be implemented?
EDIT:
Using templates users have to always pass literals as template arguments and not as function ones which is very uncomfortable:
template<int x>
int do_something()
{
static_assert(x > 0, "x must be > 0");
return x + 5;
}
int do_something(int x)
{
if(x > 0) { cout << "x must be > 0" << endl; exit(-1); }
return x + 5;
}
int var;
do_something(9); //instance 'do_something(int x)' and doesn't check validity at compile time
do_something(0); //same as above, if check was performed - compiler error should occur
do_something<9>(); //instance template 'do_something<int>()'
do_something<0>(); //produces compiler error
do_something(var); //instance 'do_something(int x)'