接收 std::pair 作为参数并从花括号列表初始化中推导出类型的模板函数

A templated function that receives std::pair as an argument and deduces the types from braced-list initialization

我正在尝试创建一个接收 std::pair 的模板函数,我希望类型为
当我调用带有花括号列表初始化的函数时,隐式推导而不指定它们。我尝试了以下代码,但它没有编译(我使用的是 visual studio 2017)。
我希望得到一些帮助来完成这项工作。
谢谢

template <typename Key, typename Value>
void foo(std::pair<Key, Value> arg)
{}

int main()
{
    foo({1.0, "some string"}); // doesn't compile
    foo(std::pair{ 1.0, "some string" }); // compiles when I specify the type this way
    return 0;
}

初始化器列表引入了所谓的 "non-deduced context",它们不能很好地处理模板参数推导。您可以改为提供额外的重载

template <typename Key, typename Value>
void foo(Key&& k, Value&& v)
{
   foo(std::make_pair(std::forward<Key>(k), std::forward<Value>(v)));
}

它只是将调用转发给您的原始函数模板,并且可以通过

调用
foo(1.0, "some string");

请注意,调用语法省略了大括号。如果您更喜欢只有一个模板,您当然可以将原始 foo 实现直接放入这个新函数模板的主体中。