字符串的类型特征
Type trait for strings
是否有一个现有的(在标准库或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"
}
相关文章:
- 如何将高维数据映射到特征类型?
- 将平面阵列重塑为复杂的特征类型
- 以特征类型作为参数的泛型函数回调
- 如何通过opencv中的程序参数定义特征类型?
- 在编译时检查特征类型保存的数据在内存中是否连续
- 专门针对特征类型的功能
- 具有特征类型输出的特征二进制 Expr
- 使用具有STL容器和STD :: vector的特征类型
- 从指针进行特征3类型的强制转换/复制(溢出uint8_t)
- 使用 python 扩展在 gdb 中打印特征类型时出现问题
- 将特征类型与 boost::bind 一起使用是否会自动违反 Eigen 的"only pass by reference"规则?
- NVIDIA NVCC 在使用模板特征类型时更改编译时间常量
- 固定大小的特征类型作为参数
- 特征类型类型定义失败,并显示 C4430
- 检查类型是否为特征 3 类型
- 传递std::迭代器,指向具有特征类型的向量
- visual studio 2012中对特征类型向量的自动矢量化表现不佳
- 子类特征类型
- 使用一个特征类型内提升图
- 特征c++类型转换