【问题标题】:Extract just the argument type list from decltype(someFunction)仅从 decltype(someFunction) 中提取参数类型列表
【发布时间】:2013-09-23 03:14:50
【问题描述】:

我有一个表示函数参数列表的可变参数模板,例如:

void myFunc (int,int,std::string) { }
template<typename... Args> class MyTemplateClass { };
...
MyTemplateClass<int,int,std::string> myConcrete; // for use with myFunc later

有什么方法可以只从 decltype(func) 中提取参数类型,以省去手动编写它们的麻烦,例如:

MyTemplateClass<something_like_decltype(myFunc)> myConcrete;

在这种情况下,即 decltype 会给我“void(int,int,string)”,但有没有办法只提取“int,int,string”部分以用于可变参数模板?

注意:我必须使用可变参数模板方法,因为在模板中它依次对每个参数类型执行处理。

【问题讨论】:

    标签: c++ templates c++11 decltype variadic


    【解决方案1】:

    这里有一个替代方法(借鉴Daniel Freysolution 的想法),使用函数模板而不是类模板:

    template <template<typename...> class C, typename R, typename... Args>
    C<Args...> apply_args(R(Args...));
    
    void f(int, bool);
    
    using MyPair = decltype(apply_args<std::pair>(f)); // = std::pair<int, bool>
    MyPair myPair{42, false};
    

    编辑:对我的解决方案的评论 x Daniel Frey's

    我的可以省去打字。他的比较惯用。事实上,在 C++ 元编程中 接受类型并返回类型的“函数”(或元函数)是 (通常)实现为模板类,其成员 type 给出 返回。因此,我更喜欢他的解决方案。

    【讨论】:

      【解决方案2】:

      以下应该有效:

      template<template<typename...> class C,typename T>
      struct apply_args;
      
      template<template<typename...> class C,typename R,typename... Args>
      struct apply_args<C, R(Args...) >
      {
          typedef C<Args...> type;
      };
      
      typedef apply_args<MyTemplateClass,decltype(myFunc)>::type MyConcrete;
      MyConcrete myConcrete;
      

      【讨论】:

        猜你喜欢
        • 2020-01-04
        • 1970-01-01
        • 2023-02-01
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-10
        • 1970-01-01
        相关资源
        最近更新 更多