Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading