这似乎是一个标准案例:
#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/