2011-11-11 49 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>'。 –