字符串的类型特征

Type trait for strings

本文关键字:特征 类型 字符串      更新时间:2023-10-16

是否有一个现有的(在标准库或Boost中(类型特征来测试一个类型是否可以表示字符串?

我在使用Boost时偶然发现了一个问题。融合:

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

我希望filter能保留"一",但它失败了,因为"一"没有衰减为指针(make_vector通过引用获取其参数,因此类型为const char (&)[4](。因此,我需要一个能让我写这样的东西的特质:

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

我知道char const *const char[N]不一定是以null结尾的字符串,但能够统一检测它们仍然很方便。该性状也可能为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++17中工作。

#include <iostream>
#include <string>
#include <type_traits>
 
template<typename T>
struct is_string
        : public std::disjunction<
                std::is_same<char *, std::decay_t<T>>,
                std::is_same<const char *, std::decay_t<T>>,
                std::is_same<std::string, 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"
}