I am playing around with some toy code using c++11 to figure out a bit more about how things work. During this I came across the following issue that simplifies down to:
template <int x, int y>
class add {
public:
static constexpr int ret = x + y;
};
constexpr int addFunc(const int x, const int y) {
return add<x,y>::ret;
}
int main() {
const int x = 1;
const int y = 2;
cout << add<x,y>::ret << endl; // Works
cout << addFunc(1,2) << endl; // Compiler error
return 0;
}
I'm using GCC 4.8.1 and the output is:
'x' is not a constant expression in template argument for type 'int'
'y' is not a constant expression in template argument for type 'int'
What exactly is the difference between the two ways I am trying to calculate add::ret
? Both of these values should be available at compile time.
constexpr
functions have to be able to be run at runtime.constexpr
functions have to be able to be run at runtime, and yourconstexpr
function would fail whenever called with any value that is not a compile-time constant, so yourconstexpr
function isn't valid. What you're looking for isn't whatconstexpr
provides, and isn't something C++ provides in another form either. What comes closest is makingaddFunc
a template function withint x
andint y
template parameters.