1

Is there a way to use constexpr without the need to create an extra variable? Take for example the code below, which maps a type to a global object. The why of the mapping should not be relevant to the question.

#include <iostream> struct S { int val; }; S one{1}; S two{2}; template<typename> constexpr S& get() = delete; template<> constexpr S& get<int>() { return one; }; template<> constexpr S& get<double>() { return two; }; auto main() -> int { constexpr auto& type = get<int>(); std::cout << type.val << std::endl; std::cout << get<double>().val << std::endl; return 0; } 

godbolt

The call to get<double>(); does not get treated as a constexpr, and it's executed at runtime (with, optimizations the call is inlined and it's equivalent to constexpr). The call to constexpr auto& type = get<int>(); does make use of constexpr do requires another variable. Just for usability, is there something to this extent std::cout << (constexpr get<int>()) << std::endl; that could be used?

6
  • 1
    C++20's consteval Commented Jan 23, 2023 at 15:01
  • That makes sense, thanks! Too bad I'm stuck with c++14. Commented Jan 23, 2023 at 15:04
  • 1
    "with, optimizations the call is inlined and it's equivalent to constexpr" why is that not ok? Commented Jan 23, 2023 at 15:05
  • there are ways to enforce compile time evaluation also in c++14. You could write a class template with val as static member, but thats possibly a step back compared to what you have Commented Jan 23, 2023 at 15:08
  • 2
    constexpr only implies that get can be evaluated at compile time. It does not imply that it is always evaluated at compile time. If you assume the latter then there is inconsistency. Whether it is called at compile time in contexts where it can be called at runtime, the compiler still decides as it does without constexpr Commented Jan 23, 2023 at 15:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.