c++ - make_tuple 的构建问题 - 数组引用

标签 c++ c++11 reference tuples pass-by-reference

我有一个类,它将对大小为 5 的数组的引用作为构造函数中的参数之一。

class sha1 {
public:
    typedef unsigned int(&type)[5];
    type digest_;
    sha1(const type digest) : digest_(digest)
    {}
};

我能够通过传递 5 的数组来实例化此类。但是用对 std::make_tuple 的调用替换它无法编译。

int main(int argc, const char* const argv[]) {
    unsigned int digest[5] = { 0 };
    const sha1 s(digest);
    const sha1 p = std::make_tuple(digest);   <-- error here
    return 0;
}

错误:

error C2440: 'initializing': cannot convert from 'std::tuple<unsigned int *>' to 'sha1'
note: No constructor could take the source type, or constructor overload resolution was ambiguous

我怎样才能做到这一点?这里的代码已经简化了很多,以便更容易解释。我想做的是使用该类作为 unordered_map 的键,并使用 emplace 插入条目,这会产生相同的错误。

我使用的是 Visual Studio 2015

这是带有 unordered_map 的代码

#include <iostream>
#include <unordered_map>

class sha1 {
public:
    typedef unsigned int(&type)[5];
    const type digest_;
    const int index_;
    sha1(const type digest, int index) : digest_(digest), index_(index)
    {}
    bool operator==(const sha1& that) const {
        return true;
    }
};

namespace std {
    template<> struct hash<sha1> {
        inline size_t operator()(const sha1& p) const {
            return 0;
        }
    };
}

int main(int argc, const char* const argv[]) {
    unsigned int digest[5] = { 0 };

    const sha1 s(digest, 10); // works

    std::unordered_map<sha1, std::string> map;

    map.insert(std::make_pair(sha1(digest, 10), "test")); // works

    map.emplace(std::piecewise_construct, std::make_tuple(digest, 10), std::make_tuple("test"));  // <-- error here

    return 0;
}

最佳答案

make_tupledecay在构造 tuple 之前传递给它的参数,因此 unsigned int(&)[5] 类型会转换为 unsigned int *,它与您的 sha1 构造函数的参数类型不匹配。

使用forward_as_tuple而不是创建一个引用元组。

map.emplace(std::piecewise_construct,
            std::forward_as_tuple(digest, 10),
            std::forward_as_tuple("test"));

关于c++ - make_tuple 的构建问题 - 数组引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31931373/

相关文章:

c++ - operator< std::set 的重载

C++ 避免两次删除内存

c++ - 当宏用作变量名时,有什么方法可以跳过宏替换(在预处理期间)?

c++ - 性能 : Reference vs. 值作为函数参数

c++ - C++中引用变量的使用

assemblies - CLR 何时尝试加载引用的程序集?

c++ - 如何访问 map 中的 vector

c++ - 根据用户输入使用 C++ 创建图形

c++ - 仅获得部分输出

c++ - 类型不可知的 getter 方法