c++ - 字符串的类型特征

标签 c++ string c++11 traits

是否有现有的(在标准库或 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/

相关文章:

结构中的字符数组

c++ - lambda:应该通过引用捕获 const 引用产生未定义的行为吗?

C++0x 嵌套初始化列表

c++ - 交换 const char* 和 std::string

C++ 函数错误

c++ - 类型转换指针和三元? : operator. 我是重新发明了轮子吗?

c++ - 我目前正在使用什么 c++ norme?

c++ - constexpr 用户定义文字 : Is it allowed?

c++ - 空终止字符 (\0) 和 `^@` 之间的区别

c++ - C++中分类字符串文字的高效内存存储和检索