[英]Type trait for strings
是否存在(在標准庫或 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
等,該 trait 也可能返回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 *, typename std::decay_t<T>>,
std::is_same<const char *, typename std::decay_t<T>>,
std::is_same<std::string, typename 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"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.