SFINAE检查运营商[]比我更困惑?

时间:2016-09-23 14:15:01

标签: c++ templates c++14 sfinae c++17

我为operator[]编写了简单的检查,但是has_subscript_op struct template instantiation选择了错误的重载:

#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

Coliru

这是GCC的错误,一般的错误,还是我在某个地方犯了一个明显的错误?

1 个答案:

答案 0 :(得分:8)

只需删除&并使用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 {};

Live example at coliru

为什么S()的检查结果错误?因为在GCC中,它被认为是0std::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的加值,您的支票不会要求密钥可以默认构建。