本文介绍了键入字符串的trait的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在(在标准库或Boost中)类型trait以测试类型是否可以表示一个字符串?

Is there an existing (in the standard library or in Boost) type trait to test whether a type could represent a string?

Boost.Fusion:

I stumbled upon an issue when using Boost.Fusion:

auto number = fusion::make_vector( 1, "one" );
auto numberName = fusion::filter< char const * >( number );

assert( numberName == fusion::make_vector( "one" ) ); // fails

我希望过滤器 one,但它失败了,因为one不会衰减到指针( make_vector 通过引用获取它的参数,因此类型是 const char (&)[4] )。因此,我需要一个trait,让我写这样的东西:

I hoped filter would retain "one", but it failed because "one" is not decayed to a pointer (make_vector takes its arguments by reference, so the type is const char (&)[4]). Consequently, I need a trait that would allow me to write something like this:

auto numberName = fusion::filter_if< is_string< mpl::_ > >( number );



我知道一个 char const * const char [N] 不一定是以null结尾的字符串,但它仍然可以方便地检测它们。 trait也可能返回 true std :: string 等。

I am aware that a char const * and a const char[N] are not necessarily null-terminated strings, but it would still be handy to be able to detect them uniformly. The trait could also possibly return true for std::string and the likes.

这样的特征存在还是我自己写?

Does such a trait exist or will I have to write my own?

推荐答案

在实现这样的特质,但我不知道它真的很强大。任何输入都将被赞赏。

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 {};

这篇关于键入字符串的trait的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:06