使用 std::tuple_element 时无效使用不完整类型的问题

sjr*_*son 3 c++ stdtuple c++14 stdhash

下面的代码为 a 实现了一个散列函数,std::tuple然后在我的代码库的不同段中使用 a std::unordered_mapof std::tuples。

// compute hash function recursively through each std::tuple element
template<class Tuple, std::size_t N>
struct tuple_hash_compute {
    static std::size_t hash_compute(const Tuple& t) {
        using type = typename std::tuple_element<N-1, decltype(t)>::type; // OFFENDING LINE
        return tuple_hash_compute<Tuple, N-1>::hash_compute(t)
            + std::hash<type>()(std::get<N-1>(t));
    }
};
// base helper
template<class Tuple>
struct tuple_hash_compute<Tuple, 1> {
    static std::size_t hash_compute(const Tuple& t) {
        using type = typename std::tuple_element<0, decltype(t)>::type; // OFFENDING LINE
        return 51U + std::hash<type>()(std::get<0>(t))*51U;
    }
};
// tuple_hash function object
struct tuple_hash {
    template<class... Args>
    std::size_t operator()(const std::tuple<Args...>& t) const {
        return tuple_hash_compute<decltype(t), sizeof...(Args)>::hash_compute(t);
    } 
    // will use std::unordered_map of std::pair too, so overload reqd
    template<class Ty1, class Ty2>
    std::size_t operator()(const std::pair<Ty1, Ty2>& p) const {
        return tuple_hash_compute<decltype(t), 2>::hash_compute(p);
    }
};
Run Code Online (Sandbox Code Playgroud)

然后,作为一个例子,我会像这样使用这个哈希函数对象,

std::unordered_map<std::tuple<int,int,int>, std::size_t, tuple_hash> agg_map;
agg_map.insert(std::make_pair(std::make_tuple(1,2,3), 0U));
agg_map.insert(std::make_pair(std::make_tuple(4,5,6), 1U));
Run Code Online (Sandbox Code Playgroud)

但是,在GCC 6.1.0和 中MSVC2015,我收到以下错误(对于上面的每个违规行都相同):

错误:不完整类型“ class std::tuple_element<2ul, const std::tuple<int,int,int>&>”的无效使用

我不完全确定是什么导致了这个错误(尽管它可能是由于std::tuple通过模板参数传递的“抽象” Tuple)或如何解决它,所以任何帮助表示赞赏。

Pio*_*cki 5

对于如下声明的参数:

const Tuple& t
Run Code Online (Sandbox Code Playgroud)

decltype(t) 产量:

const Tuple&
Run Code Online (Sandbox Code Playgroud)

类似地,对于声明为的参数:

const std::pair<Ty1, Ty2>& t
Run Code Online (Sandbox Code Playgroud)

decltype(t) 产量:

const std::pair<Ty1, Ty2>&
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,生成的类型都是对类元组类型的引用。但是,std::tuple_element不是专门用于引用,这意味着编译器回退到主要的、未定义的类模板:

template <size_t I, typename T> class tuple_element;
Run Code Online (Sandbox Code Playgroud)

你想要的是Tuple前std::pair<Ty1, Ty2>一种情况下的平原,后一种情况下。

  • 如果你需要使用`decltype`,你可以使用`std::decay_t&lt;decltype(t)&gt;`。 (2认同)