Jue*_*gen 4 c++ callable signature template-argument-deduction c++17
是否以及如何从 C++17 中的任何可调用函数中推断出签名类型?片段:
template <typename T>
struct MyFunction;
template <typename R, typename... Args>
struct MyFunction<R(Args...)>
{
};
template <typename Callable>
auto deduceSignature(Callable&& c)
{
// using Signature = ???;
// return MyFunction<Signature>{ ???};}
}
Run Code Online (Sandbox Code Playgroud)
我想在return语句中使用 use 类模板参数推导。在客户端代码中我想这样写:
std::int8_t freeFunction(std::int8_t x)
{
return x;
}
auto c1 = deduceSignature(&freeFunction);
auto c2 = deduceSignature([](std::int8_t x){
return x;
});
Run Code Online (Sandbox Code Playgroud)
std::function可以从任何可调用对象构造,并且可以推导出签名 (C++17 起)。我们可以用它来创建一个提取签名的类型特征。
#include <functional>
template <typename T>
struct get_signature;
template <typename R, typename... Args>
struct get_signature<std::function<R(Args...)>> {
using type = R(Args...);
};
template <typename Callable>
auto deduceSignature(Callable&& c)
{
using Signature = typename get_signature<decltype(std::function{c})>::type;
}
int main() {
deduceSignature([](int a){return 5;});
}
Run Code Online (Sandbox Code Playgroud)