推导变量模板函数的参数失败

时间:2018-01-09 17:15:59

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

这似乎是一个标准情况:

failed to make a valid plan

如果您明确告诉编译器#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> > >*)’

1 个答案:

答案 0 :(得分:4)

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

所以

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()以在第一个位置接收指向矢量参数v的指针,并按如下方式调用Foo()

Foo(&foo, string("asdf"), string("qwerty"));
相关问题