我在学习概念和模板。我正在尝试创建一个函数模板,它将调用另一个函数模板。目前,它与lambda一起工作,但不具有正常的功能。
// This also works with lambda but not the normal function:
//void callFunc(std::regular_invocable<T> auto invocable)
template<typename T>
void callFunc(auto invocable)
{
invocable(T(5));
}
// Doesn't work, whether I use "T" or "auto"
//template<typename T>
void testFuncToPass(const auto& a)
{
std::cout << a << " CALLED\n";
}
//...
auto lambda = [](const auto& a){std::cout << a << " CALLED\n";};
//callFunc<int>(testFuncToPass); // ERROR
callFunc<int>([](const auto& a){std::cout << a << " CALLED\n";});
callFunc<int>(lambda);它说:“错误:没有调用'callFunc‘的匹配函数。忽略候选模板:无法推断模板参数’可调用:自动‘”
我想做的是可行的吗?我还尝试使用模板模板参数,但似乎只适用于类型,而不适用于函数。
发布于 2021-06-01 03:31:45
你的印象是
auto lambda = [](const auto& a){std::cout << a << " CALLED\n";};等于
template<typename T>
void lambda(const T& a) { std::cout << a << " CALLED\n"; }但事实并非如此。它实际上相当于:
struct SomeType {
template<typename T>
void operator()(const T& a) const { std::cout << a << " CALLED\n"; }
};
SomeType lambda;有趣的事实:如果您的lambda捕获值和/或引用,它们将成为该结构的私有成员,并将lambda标记为可变,只需删除const即可。Lambdas实际上只是在函子之上的语法糖。
是我想要做的吗?
不幸的是,与目前的标准不同。可以接受模板类型作为参数(通过一些看起来古怪的语法),但是函数模板目前仍然不在表中。
您几乎必须像我的示例中那样声明带有模板operator()的结构或类,或者将它们包装在lambda中:
callFunc<int>([](auto const& a){testFuncToPass(a);});https://stackoverflow.com/questions/67782332
复制相似问题