gpt4 book ai didi

c++ - 如何检测 operator[] 是否适用于 Type?

转载 作者:行者123 更新时间:2023-11-30 01:43:58 24 4
gpt4 key购买 nike

我想写这样的函数模板

template< typename T >
void foo( T& obj ){
obj[0] = xxxxxx;
}

其中 T 必须有 operator[] 适用。
T 可以是任何类型的数组、std::vector、std::array 或任何其他类型。所以,我不能使用 T 作为所有这些的父类(super class)。我认为它应该类似于 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;
}

参见 cppreference page如何实现 std::experimental::is_detected

关于c++ - 如何检测 operator[] 是否适用于 Type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36963795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com