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?

0 Answers0