【问题标题】:Extract a typedef/using definition from a template class从模板类中提取 typedef/using 定义
【发布时间】:2016-04-25 18:45:35
【问题描述】:

有没有办法从模板类中提取 typedef?例如,这是我想做的:

template<typename T, typename... Args>
class Foo{
public:
   typedef T(*Functor)(Args...);
   Foo() = default;
};

template<typename T, typename... Args>
Foo<T, Args...> make_foo(T(*f)(Args...)){
    return Foo<T, Args...>;
}

int bar(int i){
    return i * 2;
}

using type = make_foo(bar)::Functor;

我不能这样做。但是,我可以这样做:

using type = Foo<int, int>::Functor;

这种方式违背了我的目的。有什么方法可以包装一个函数,以便我可以以类型形式提取它?

【问题讨论】:

    标签: c++ templates types casting


    【解决方案1】:

    decltype 够好吗?

    using type = decltype(make_foo(bar))::Functor;
    

    【讨论】:

    • 哇,这么明显...谢谢。
    【解决方案2】:

    使用decltype:

    template<typename T, typename... Args>
    class Foo{
    public:
       typedef T(*Functor)(Args...);
       Foo() = default;
    };
    
    template<typename T, typename... Args>
    Foo<T, Args...> make_foo(T(*f)(Args...)){
        return Foo<T, Args...>{}; // Small compilation error fixed here.
    }
    
    int bar(int i){
        return i * 2;
    }
    
    using type = decltype(make_foo(bar))::Functor;
    

    这个操作符返回它所输入的表达式的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2016-03-21
      相关资源
      最近更新 更多