Type trait for strings
I gave a shot at implementing such a trait, but I am not sure it is really robust. Any input will be appreciated.
template <typename T>
struct is_string
: public mpl::or_< // is "or_" included in the C++11 library?
std::is_same< char *, typename std::decay< T >::type >,
std::is_same< const char *, typename std::decay< T >::type >
> {};
assert ( ! is_string< int >::value );
assert ( is_string< char * >::value );
assert ( is_string< char const * >::value );
assert ( is_string< char * const >::value );
assert ( is_string< char const * const >::value );
assert ( is_string< char (&)[5] >::value );
assert ( is_string< char const (&)[5] >::value );
// We could add specializations for string classes, e.g.
template <>
struct is_string<std::string> : std::true_type {};
This should work in C++17.
#include <iostream>
#include <string>
#include <type_traits>
template<typename T>
struct is_string
: public std::disjunction<
std::is_same<char *, typename std::decay_t<T>>,
std::is_same<const char *, typename std::decay_t<T>>,
std::is_same<std::string, typename std::decay_t<T>>
> {
};
int main()
{
std::cout << std::boolalpha;
std::string str = "i am a string";
std::cout << is_string<decltype(str)>::value << std::endl; // "true"
std::cout << is_string<decltype("i am a string literal")>::value << std::endl; // "true"
}