[英]How to declare the signature of generic higher order functions with concepts in c++ 20?
The following code declares that the function returned by the function Foo
must model a function that takes 1 int and returns an int.以下代码声明 function Foo
返回的 function 必须是 model 和 function,它接受 1 个 int 并返回一个 int。
#include <functional>
#include <concepts>
std::convertible_to<std::function<int(int)>> auto Foo(){
return [](int x){
return 1;
};
}
int main(){
return Foo()(1);
}
If I now change the code and declare the returned function to be templated with auto like so如果我现在更改代码并声明返回的 function 像这样使用 auto 进行模板化
#include <functional>
#include <concepts>
std::convertible_to<std::function<int(auto)>> auto Foo(){
return [](auto x){
return 1;
};
}
int main(){
return Foo()(1);
}
I can't simply change the concept and insert auto as in std::convertible_to<std::function<int(auto)>>
我不能像std::convertible_to<std::function<int(auto)>>
那样简单地改变概念并插入auto
Is there a workaround or special notation for this?是否有解决方法或特殊符号?
https://godbolt.org/z/sKf3Eb4MM https://godbolt.org/z/sKf3Eb4MM
This may work under some circumstances though certainly not everything.这可能在某些情况下有效,但肯定不是所有情况。
#include <concepts>
/// A type that converts to anything as a stand in for the
/// unknown type.
struct Auto
{
template <typename T>
operator T();
template <typename T>
operator T&();
template <typename T>
operator T&&();
};
template <typename Fn, typename R, typename ...Args>
concept callable = requires (Fn fn, Args ... args){
{fn(args...)}->std::same_as<R>;
};
callable<int,Auto> auto Foo(){
return [](auto x)->int{
return (int)(x+1);
};
}
int main(){
return Foo()(1);
}
https://godbolt.org/z/xzbx55bG7 https://godbolt.org/z/xzbx55bG7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.