Reputation: 333
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 ?
Upvotes: 0
Views: 410
Reputation: 3106
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
Upvotes: 1
Reputation: 172934
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*
.
Upvotes: 2