2011-11-11 36 views
3

是否存在(在标准库或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将保留“一”,但失败了,因为“一个”不衰减到指针(make_vector由接受它的参数参考,所以类型是const char (&)[4])。因此,我需要一个特质,让我写的是这样的:

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

我知道,一个char const *const char[N]不一定空值终止字符串,但它仍然是得心应手能够均匀检测它们。该特征还可能为std::string等等返回true

这样的特质是否存在或我必须自己写?

+0

怎么样'static_cast (“one”)'?或者是一个将数组转换为指针的通用模板? –

+0

@KerrekSB:在函数调用中封装每个字符串似乎都是一个真正的负担,但是可以使用函数模板来测试类型是否可以转换为字符指针... –

+0

Just fyi,you're缺少assert()中的关闭karen。 – semisight

回答

6

我在实施这样一个特质方面做了一些尝试,但我不确定它是否真的很健壮。任何输入将不胜感激。

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

'or_'不包含在11,no。我相信相当于'std :: integral_constant :: value || std :: is_same <...> :: value>'。 –