如何解决我可以从旧式函数签名中获取参数包吗?
我想声明一个方法 - 可变参数 - 其签名来自作为模板参数的“旧式”函数签名。
您可以使用函数签名声明,例如,std::function
,例如,
std::function<int(float,float)> f;
现在我想要一个模板,它采用这样的函数签名并以某种方式声明一个方法:
template <typename F>
struct Foo {
[F's-return-type] Method(F's-Arg-pack]...) { ... }
};
因此,如果您按如下方式实例化它,您将获得如下方法:
Foo<int(float,float)> foo;
int x = foo.Method(1.0f,2.0f);
或者也许有不同的方法来做到这一点?
解决方法
您可以使用非常简单的部分特化反汇编 F
:
template <class F>
struct Foo;
template <class Ret,class... Params>
struct Foo<Ret(Params...)> {
Ret Method(Params...) { /* ... */ }
};
,
当然啦!结果类型很简单,就是std::function::result_type
。提取参数类型不太直接,需要部分类特化(至少在我的解决方案中):
template<class F> struct Foo;
template<class R,class... Args>
struct Foo<std::function<R(Args...)>
{
R Method(Args... args) { ... }
};
,
您需要部分专业化,每种功能一个。 希望对于常规功能(所以不是 abominable functions),有更少:
template <class Sig>
struct Foo;
template <typename Ret,typename... Ts>
struct Foo<Ret(Ts...)> {
Ret Method(Ts...) const { /* .. */ }
};
// C-ellipsis (printf-like)
template <typename Ret,typename... Ts>
struct Foo<Ret(Ts...,...)> {
Ret Method(Ts...,...) const { /* .. va_arg and co */ }
};
对于方法,组合更大(cv-qualifier (x4),ref-qualifier (x3),so 24)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。