是否有现有的(在标准库或 Boost 中)类型特征来测试一个类型是否可以表示一个字符串?
我在使用 Boost.Fusion 时偶然发现了一个问题:
auto number = fusion::make_vector( 1, "one" );
auto numberName = fusion::filter< char const * >( number );
assert( numberName == fusion::make_vector( "one" ) ); // fails
我希望 filter
会保留“one”,但它失败了,因为“one”没有衰减为指针(make_vector
通过引用获取其参数,因此类型是 const char (&)[4]
)。因此,我需要一个 trait 来让我写出这样的东西:
auto numberName = fusion::filter_if< is_string< mpl::_ > >( number );
我知道 char const *
和 const char[N]
不一定是空终止字符串,但它仍然很方便统一检测。对于 std::string
等,该特征也可能返回 true
。
是否存在这样的特性,还是我必须自己编写?
最佳答案
我试过实现这样的特性,但我不确定它是否真的可靠。任何输入将不胜感激。
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 {};
关于c++ - 字符串的类型特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8097534/