简体   繁体   中英

cpp function that returns value depending on the template type

I would like to convert the following pseudo-code into c++17 code:

template<class T>
char* foo(){
    if(T is a float) return "we have a float"
    if(T is a int) return "we have a int"
    if(T is a double) return "we have a double"
    return "unknown"
}

Such that I can use it like

LOGD("%s", foo<float>());
LOGD("%s" foo<double>());

Is that possible?

You can use std::is_same to check the types, and since you mentioned C++17, you can use constexpr if , which checks the condition at compile-time, and according to the result the statement-true/false would be discarded.

template<class T>
const char* foo(){
    if constexpr (std::is_same_v<T, float>) return "we have a float";
    else if constexpr (std::is_same_v<T, int>) return "we have a int";
    else if constexpr (std::is_same_v<T, double>) return "we have a double";
    else return "unknown";
}

Before C++17 you can also use the original if and the condition would be checked at run-time.

BTW: The c-style string literal has the type of const char[] and can't be converted char* since C++11, so better to change the return type to const char* .

I would use a generic class to contain the message:

template <class T> struct message { static const char * const value; };

template <> 
constexpr const char *message<int>::value = "we have an int";

template <class T>
const char *foo() { return message<T>::value; }

For every new type you want to include, you need to add yet another case for your function, while with a generic class you only need to define the new message:

template <> 
constexpr const char *message<float>::value = "we have a float";

See https://gcc.godbolt.org/z/_mhHwI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM