我为operator []编写了简单的检查,但是has_subscript_op结构模板实例化选择了错误的重载:
#include <iostream>
#include <type_traits>
#include <string>
#include <map>
template<class, class, class = void>
struct has_subscript_op : std::false_type
{ };
template<class T, class S>
struct has_subscript_op<T, S, std::void_t<decltype(&std::declval<T>()[S()])>> : std::true_type
{ };
int main()
{
//true, nice
std::cout << "int[][int]: " << has_subscript_op<int[], int>::value << std::endl;
//false, nice
std::cout << "int[][float]: " << has_subscript_op<int[], float>::value << std::endl;
//true, nice
std::cout << "std::string[int]: " << has_subscript_op<std::string, int>::value << std::endl;
//true, WAT?
std::cout << "std::map<std::string, std::string>[int]: " << has_subscript_op<std::map<std::string, std::string>, int>::value << std::endl;
}
我正在使用GCC 6.2.0
这个GCC错误,一般错误,还是我在某个地方犯了一个明显的错误?
解决方法:
只需放下&并使用declval作为键:
template<class T, class S>
struct has_subscript_op<T, S, std::void_t<decltype(std::declval<T>()[std::declval<S>()])>> : std::true_type {};
为什么用S()检查给出了错误的结果?因为在GCC中,它被认为是0.一个std :: string可以用指针构造,而0恰好是一个空指针常量.
其他编译器不应该处理S(),因为它在C 14中为0.
你可以试试自己:
std::map<std::string, std::string> test;
// compile fine, segfault at runtime
auto a = test[0];
// compile error!
auto b = test[2]
使用std :: declval检查效果更好,因为它不是0,不是2而是普通的int.奖金,使用declval,您的支票不需要密钥是默认可构造的.
标签:c,templates,c14,sfinae,c17 来源: https://codeday.me/bug/20190724/1524411.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。