【发布时间】:2021-06-28 19:25:56
【问题描述】:
尝试将 lambda 函数传递给模板工厂函数,该函数以传递函数的函数参数为模板,导致 gcc-10.2.0 报告 no matching function for call to ‘test(main()::<lambda(int, double)>)’。
当我在 lambda 函数前面添加 + 强制转换为函数指针时,它似乎确实有效,但我不明白为什么有必要这样做。为什么转换不会自动发生?有什么办法可以做到这一点?
我也尝试将std::function<void(TArgs...)> test_func 作为make_test 声明中的参数,但这给了我同样的no matching function for call 错误。
#include <iostream>
template <typename... TArgs>
struct test_type {
test_type(void(TArgs...)) {};
};
template <typename... TArgs>
test_type<TArgs...> make_test(void test_func(TArgs...)) {
return test_type<TArgs...>{test_func};
}
int main() {
auto test_object = make_test([](int a, double b) { std::cout << a << b << "\n"; });
return 0;
}
编辑
我想知道是否有某种方法可以使其与类型特征一起使用。类似于以下内容。虽然我不知道如何从模板参数中获取参数列表。
template <typename F>
test_type<get_arg_list<F>> make_test(std::function<F>&& f) {
return test_type<get_arg_list<F>>{std::forward(f)};
}
【问题讨论】:
-
@AndyG 不管有没有
std::function,我认为OP是在问如何从lambda中推断出参数类型。 -
@RichardCritten 因为
auto test_object = test_type<int, double>{[](int a, double b) { std::cout << a << b << "\n"; }}按预期工作。至少当我指定构造函数取std::function<void(TArgs...)>时是这样,但工厂函数由于某种原因不能这么说。
标签: c++ lambda variadic-templates c++20