将列表初始化对象传递给std :: make_tuple

时间:2016-12-29 03:25:35

标签: c++

是否有原因std::make_tuple不接受列表初始化对象的参数?

#include <string>
#include <map>
#include <cstdint>

class FileInfo
{
public:
    FileInfo() = default;
    FileInfo(const std::string &name, uint64_t size) : mName(name), mSize(size) { }

    bool operator == (const FileInfo& other) const
    {
        return mName == other.mName;
    }

private:
    std::string mName;
    uint64_t mSize = 0;
};

void function(FileInfo fileInfo) { } 

using Modifications = std::map<std::string, std::tuple<std::string, FileInfo, FileInfo>>;

int main(int argc, char *argv[])
{
    Modifications modifications{
        { "f1", std::make_tuple("changed", FileInfo{ "f1", 1 }, FileInfo{ "f1", 2 }) },
        { "f2", std::make_tuple("removed", FileInfo{ "f2", 1 }, FileInfo{}) },
        { "f3", std::make_tuple("added", FileInfo{}, { "f3", 2 }) } // Error
    };

    function({ "f3", 2 }); // OK

    return 0;
}

地图中的第三对出现以下错误:

  

错误C2660&#39; std :: make_tuple&#39;:函数不带3个参数

这个错误对我没有意义。当我明确声明std::make_tuple的类型为Modifications时,为什么&#39; t std::map<std::string, std::tuple<std::string, FileInfo, FileInfo>>接受第三个参数?是否存在编译器限制或者这在标准中被省略了?

注意:此问题与从括号列表构建元组无关:initialize-an-stdarray-of-tuples-with-curly-braces

1 个答案:

答案 0 :(得分:2)

正如评论中指出的那样,错误在于你没有在调用FileInfo函数时构造make_tuple对象,C ++编译器无法知道你想要什么第三个目标。如果您将呼叫更改为此类

std::make_tuple<std::string, FileInfo, FileInfo>("added", FileInfo{}, { "f3", 2 })

然后代码也会工作,你需要make_tuple函数来推断出参数列表中事物的类型。

The compiler cannot deduce the type of an initializer list in a template argument