Search code examples
c++c++17c++14conditional-operator

C++ compile time ternary conditional


Please, help me to figure out syntax of compile time ternary conditional in C++:

#include <iostream>
#include <type_traits>
int main(void)
{
 //const auto y = constexpr(std::is_null_pointer_v<decltype(nullptr)>) ? 777 : 888.8;
 const auto y = constexpr(std::is_null_pointer_v<decltype(nullptr)> ? 777 : 888.8);
 std::cout<<y<<std::endl;
}

Both of the options above give me error: expected primary-expression before ‘constexpr’ (gcc-11.2.0; compiled with g++ -std=c++17).

Thank you very much for your help!


Solution

  • Although one solution is provided while I program it, I suggest other solution: making your consteval tenary function template, As it can handle different type in it.

    template<bool T,auto A, auto B>
    consteval auto tenary() {
        if constexpr (T) {
            return A;
        }
        else {
            return B;
        }
    }
    
    #include <iostream>
    #include <type_traits>
    int main(void)
    {
        const auto y = tenary<std::is_null_pointer_v<decltype(nullptr)>,777,888.8>();
        std::cout << y << std::endl;
    }