I come across Demystifying constexpr, and am a little confused about the examples in this post.
According to the post, constexpr function definition is like this:
A constexpr function is able to compute its result at compilation time, if its input is known at compilation time.
In other words, any function that has "everything it needs" to compute its result at compile-time, can be a constant expression.
For add function:
int add(int a, int b)
{
return a + b;
}
Although the function is constexpr, you can use it with runtime value just the same:
int main(int argc, char argv)
{
return add(argc, argc);
}
But for another function:
int add_vectors_size(const std::vector<int> & a, const std::vector<int> & b)
{
return a.size() + b.size()
}
The explanation of it can't be used as "constexpr" is:
The compile time input are two vectors. Can we know at compile time the size of a vector? The answer is no. Thus, add_vectors_size cannot be a constant expression. We don't have "everything we need".
But per my understanding, for the first case, the argc value also can't be known during compile-time, and its value should be got at running time, correct? So how to understand constexpr function has "everything it needs" to compute
its result at compile-time?
add(argc, argc)is not known at compile-time;add(2, 3)is - M.Madd_vectors_sizecan't beconstexpris that there is no valid inputs. (A constexpr function must have at least 1 possible set of inputs which is known at compile-time) - M.M