【发布时间】:2016-11-20 07:21:53
【问题描述】:
我知道现代 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;
}
换句话说,我想为函数提供未知数量的不同类型的参数,但最后一个参数是 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
【问题讨论】:
-
为什么 lambda/callable 必须是最后一个参数而不是第一个参数,makes this trivial?
-
首先我确实这样做了。这是微不足道的,但我现在正在处理的使用我提出的构造的代码并不意味着自动生成。它旨在由用户编写。将组合子指定为最后一个参数,因为它更美观且语义更正确。这很容易说:
combine this and that with this combinator而不是combine with this combinator this and that
标签: c++ gcc c++14 variadic-templates variadic-functions