在下面的代码片段中,我尝试将 lambda 转换为我自己的函数对象,并使用基于 invocable_r 类型特征的概念对其进行约束。然而 gcc 拒绝它。
#include <concepts>
#include <cstdio>
template <typename Fn, typename R, typename... Args>
concept invocable_r = std::is_invocable_r<R, Fn, Args...>::value;
template <typename R, typename... Args>
class function
{
template <invocable_r<R, Args...> Cb>
function(Cb fn) {
printf("Converting constructor invoked!\n");
}
};
int main()
{
function<void()> hello = [](){};
}
错误:
error: conversion from 'main()::<lambda()>' to non-scalar type 'function<void()>' requested
我似乎找不到问题所在。怎么了?
最佳答案
您定义的 function
模板错误。您的版本接受多个参数,当您希望有一个特定类型的参数时。
您需要使用模板特化。你也忘记了 public:
:
#include <concepts>
#include <cstdio>
template <typename Fn, typename R, typename... Args>
concept invocable_r = std::is_invocable_r<R, Fn, Args...>::value;
template <typename T>
class function;
template <typename R, typename... Args>
class function<R(Args...)>
{
public:
template <invocable_r<R, Args...> Cb>
function(Cb fn) {
printf("Copy constructor invoked!\n");
}
};
int main()
{
function<void()> hello = [](){};
}
https://godbolt.org/z/xrvr3sMj3
你的版本必须这样使用:
int main()
{
function<void> hello = [](){};
}
https://godbolt.org/z/xvGd1s4az
顺便说一句,有 std::invocable概念,所以你介绍了一些 std 已经涵盖的东西。
关于c++ - 错误 : conversion from 'main()::<lambda()>' to non-scalar type 'function<void()>' requested,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74772606/