如何检测运算符[]是否适用于Type

How to detect if operator[] applicable to Type?

本文关键字:是否 适用于 Type 运算符 何检测 检测      更新时间:2023-10-16

我想写这样的函数模板

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");