Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator and if constexpr

I have situations where sometimes based on some bool I want to call 2 constexpr functions that return different types and assign it to auto constant.

Unfortunately ternary operator needs types to be "similar".

I have workaround in the code below but it is quite verbose. Is there a better way?

#include <iostream>
#include <string>

constexpr int get_int(){
    return 47;
}

constexpr std::string_view get_string(){
    return "47";
}

constexpr bool use_str = false;

constexpr auto get_dispatch(){
    if constexpr(use_str){
        return get_string();
    } else{
        return get_int();
    }

}
int main()
{
    // what I want : constexpr auto val =  use_str ? get_string():get_int();
    // what works:
    constexpr auto val = get_dispatch();
    std::cout << val << std::endl;
}
like image 239
NoSenseEtAl Avatar asked Apr 01 '26 14:04

NoSenseEtAl


1 Answers

Another option is to use tag dispatch:

constexpr int get(std::false_type) {
    return 47;
}

constexpr std::string_view get(std::true_type) {
    return "47";
}

int main() {
    constexpr auto val = get(std::bool_constant<use_str>{});
    std::cout << val << std::endl;
}
like image 95
Evg Avatar answered Apr 04 '26 08:04

Evg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!