如何检测运算符[]是否适用于Type
How to detect if operator[] applicable to Type?
我想写这样的函数模板
template< typename T >
void foo( T& obj ){
obj[0] = xxxxxx;
}
其中T必须具有适用的运算符[]
T可以是任何类型的数组、std::vector、std:∶array或任何其他类型。所以,我不能用T作为所有它们的超类。我认为它应该是类似std::type_traits风格的东西。
template<class T>
using LvalueIndexable = decltype(std::declval<T&>()[1]);
template<class T, class U = void>
using RequiresLvalueIndexable
= typename std::enable_if<std::experimental::is_detected<LvalueIndexable, T>{},
U>::type;
template< typename T, typename = RequiresLvalueIndexable<T> >
void foo( T& obj ){
obj[0] = xxxxxx;
}
有关如何实现std::experimental::is_detected
,请参阅cppreference页面。
有几种方法可以限制模板类型:
1) 将函数模板声明为私有类方法,然后从公共重载方法中调用它,如下所述;
2) 使用Boost静态断言和is_base_of
来比较模板和类型,请参见此处;
3) 或包括type_traits
并使用断言static_assert(is_same<T, float>::value, "Error message");
相关文章:
- __attribute__(优化(0))) 是否适用于"recursively"?
- 结构化绑定是否适用于 std::vector?
- 继承函数是否适用于 C++ 中的基类元素或派生类元素?
- 多态性是否适用于值?或者在按(基)值返回时使用派生类的移动构造函数
- 如何检测运算符[]是否适用于Type
- gcc-fdiagnostics颜色是否适用于Windows
- 英特尔 tbb 任务调度是否适用于 DBMS
- C++11 正则表达式是否适用于 UTF-8 字符串
- 未定义的行为是否适用于 asm 代码
- CUDA TCC 驱动程序是否适用于 Windows 上的 geforce 卡
- HID 设备编程 - 它是否适用于C++(SETUPAPI.dll 和 HID.dll)
- 关于"distinct addresses"的规则是否适用于 new 创建的对象?
- 名称篡改是否适用于c++中的虚拟函数
- 多态是否适用于在C中传递的c++对象引用?
- 如何发现休眠是否适用于Windows用户(使用c++)
- 这个时钟是否适用于Intel i3 ?
- boost::variant是否适用于std::string
- RVO 是否适用于"new"?
- 对齐说明符是否适用于"新"?
- Poco 是否适用于 LLVM 标准C++库