加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用函数的返回类型和参数类型作为模板类型

发布时间:2020-12-16 09:21:51 所属栏目:百科 来源:网络整理
导读:参见英文答案 Function template return type deduction????????????????????????????????????5个 是否有可能找出函数的返回类型和参数类型并将它们用作模板类型?请考虑以下示例: template typename ret,typename inclass Bar { // Some code}int foo(floa
参见英文答案 > Function template return type deduction????????????????????????????????????5个
是否有可能找出函数的返回类型和参数类型并将它们用作模板类型?请考虑以下示例:

template <typename ret,typename in>
class Bar {
  // Some code
}

int foo(float x) {
  return 0;
}

int main() {
  Bar<int,float> b; // Can this be done automatically by inspection of foo at compile time?
}

我可以使用foo的函数签名来设置Bar的模板类型吗?

解决方法

是的先生.

template <class Function>
struct BarFor_;

template <class Ret,class In>
struct BarFor_<Ret(*)(In)> {
    using type = Bar<Ret,In>;
};

template <auto function>
using BarFor = typename BarFor_<decltype(function)>::type;

现在您可以通过以下方式获取类型:

BarFor<foo> b;

See it live on Coliru

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读