Dr.*_*tix 2 c++ gcc variadic-functions variadic-templates c++14
我知道现代C++中的可变参数模板是什么,但是我无法绕过它以便能够编写如下代码:
#include <iostream>
#include <sstream>
using namespace std;
template <typename... Args, typename Combinator>
auto combine(Args... args, Combinator combinator)
{
auto current_value = combinator(args...);
return current_value;
}
int main() {
auto comb = combine(1, "asdf"s, 14.2,
[](const auto& a, const auto& b, const auto& c) {
stringstream ss;
ss << a << "\n";
ss << b << "\n";
ss << c << "\n";
return ss.str();
});
return 0;
}
Run Code Online (Sandbox Code Playgroud)
换句话说,我想给函数提供一个未知数量的不同类型的参数,但最后一个参数是lambda或用于以某种方式组合参数的任何可调用对象.这个例子看起来纯粹是学术性的,但在这个例子的基础上,我想构建更多时髦的代码,但首先我需要这个来编译.希望你能帮忙!
我无法编译.我不知道我错过了什么.
以下是GCC吐口水:
In function 'int main()':
21:6: error: no matching function for call to 'combine(int, std::basic_string<char>, double, main()::<lambda(auto:1&, auto:2&, auto:3&)>)'
21:6: note: candidate is:
7:6: note: template<class ... Args, class Combinator> auto combine(Args ..., Combinator&&)
7:6: note: template argument deduction/substitution failed:
21:6: note: candidate expects 1 argument, 4 provided
Run Code Online (Sandbox Code Playgroud)
可变参数模板必须是最后一个参数,因此可以推导出它,请参见模板参数推导
非推断的上下文
7)参数P是参数包,并不出现在参数列表的末尾:
Run Code Online (Sandbox Code Playgroud)template<class... Ts, class T> void f1(T n, Ts... args); template<class... Ts, class T> void f2(Ts... args, T n); f1(1, 2, 3, 4); // P1 = T, A1 = 1: deduced T = int // P2 = Ts..., A2 = 2, A3 = 3, A4 = 4: deduced Ts = [int, int, int] f2(1, 2, 3, 4); // P1 = Ts...: Ts is non-deduced context
您应该将其更改为:
#include <iostream>
#include <sstream>
using namespace std;
template <typename... Args, typename Combinator>
auto combine(Combinator combinator, Args&&... args)
{
auto current_value = combinator(std::forward<Args>(args)...);
return current_value;
}
int main() {
auto comb = combine([](const auto& a, const auto& b, const auto& c) {
stringstream ss;
ss << a << "\n";
ss << b << "\n";
ss << c << "\n";
return ss.str();
},
1, "asdf"s, 14.2);
std::cout << comb;
return 0;
}
Run Code Online (Sandbox Code Playgroud)