I am running into a trouble of understanding how functions, especially template functions and local variables behave during the compilation time.
So this code works well with std::get
:
enum class UserInfoFields{name, email, address};
using UserInfo = std::tuple<std::string, std::string, std::string>;
int main()
{
UserInfo s{"Edmund", "[email protected]", "Denver street 19"};
std::cout << std::get<static_cast<size_t>(UserInfoFields::name)>(s) << std::endl;
return 0;
}
This from my understanding is because std::get
is a template function and it requires a template argument to be known during the compilation. That makes sense as static_cast<...
gives us the value during the compilation time.
What I do not understand, if I change the main()
code to this:
int main()
{
UserInfo s{"Edmund", "[email protected]", "Denver street 19"};
auto a = static_cast<size_t>(UserInfoFields::name);
std::cout << std::get<a>(s) << std::endl;
return 0;
}
This is not allowed. I know that I have to use constexpr
but I want to know, why exactly the second code does not work?
You wrote yourself that
std::get
is a template function and it requires a template argument to be known during the compilation
The value of a local variable is not (in the general case) known during compilation; a local variable's value is a runtime property. As such, a local variable cannot be used as a template argument.
If you want to use it as one, you have to make it a compile-time value. This is achieved by making it constexpr
(as you've also stated in the question).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With