Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::get does not work with variables?

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?

like image 206
aikhs Avatar asked Feb 04 '23 18:02

aikhs


1 Answers

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).

like image 187
Angew is no longer proud of SO Avatar answered Feb 06 '23 11:02

Angew is no longer proud of SO