c++ - 为 Variadic 模板函数推导参数失败

标签 c++ c++11 templates variadic-templates template-argument-deduction

这似乎是一个标准案例:

#include <iostream>
#include <vector>
#include <utility>
#include <tuple>

using namespace std;

template <typename... T>
using VType = vector<tuple<T...>>;

template <typename... T>
void Foo(const T&... t, VType<T...>* v) {
    v->push_back(std::make_tuple(t...));
}
int main() {
    // your code goes here
    VType<string, string> foo;
    Foo(string("asdf"), string("qwerty"), &foo);
    return 0;
}

如果你显式地告诉编译器Foo<string, string>它工作正常,无法推断:

error: no matching function for call to ‘Foo(std::__cxx11::string, std::__cxx11::string, VType<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >*)’

此函数按预期工作:

template <typename... T>
void Bar(const std::tuple<T...> t, VType<T...>* v) {
  v.push_back(t); 
}

最佳答案

可变参数列表的类型只能在最后位置推导。

所以

template <typename... T>
void Foo(VType<T...>* v, const T&... t) {
    v->push_back(std::make_tuple(t...));
}

之所以有效,是因为 t ... 参数位于最后位置

template <typename... T>
void Foo(const T&... t, VType<T...>* v) {
    v->push_back(std::make_tuple(t...));
}

给出错误,因为 t... 不在最后一个位置。

解决方案:修改Foo(),在第一个位置接收指向 vector 参数v的指针,然后调用Foo()如下

Foo(&foo, string("asdf"), string("qwerty"));

关于c++ - 为 Variadic 模板函数推导参数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48173457/

相关文章:

c++ - 通过翻转单元格组用零填充二维数组

c++ - C++11 中的 CRTP 调度

c++ - 访问类私有(private)成员的自定义优先级队列比较器

c++ - 将内容从多容器复制到单个容器

c++ - 这是多么令人烦恼的解析?

c++ - 在 64 位中进行组合乘除运算的最准确方法是什么?

c++ - 初始化 shared_ptr 成员变量,new vs make_shared?

c++ - 使用 std::find 根据字符串 vector 检查字符串的问题

c++ - 调用模板类构造函数

c++ - 为什么需要void_t检查成员类型的存在?