【问题标题】:How to use typename instead of typedef?如何使用 typename 而不是 typedef?
【发布时间】:2015-05-30 17:08:05
【问题描述】:

我有以下代码sn-p:

template <class T>
int foo(T (*f)()) {
    typedef T (*func)();
    typedef functor<T, func> F; //this line 

    // ...
}

如您所见,我使用 typedef 作为函数指针 (func),但我想删除它以简化我的代码。我试过这个:

template <class T>
int foo(T (*f)()) {
    typedef functor<T, typename f> F;

    // ...
}

但这不会编译。在一行中将完整的 typedef 拼写为 F 的正确方法是什么?

【问题讨论】:

  • 嗯?但是func 是函数指针类型,而不是模板。那条线到底是什么意思?
  • 你需要decltype(f)
  • @T.C.,谢谢,效果很好。

标签: c++ templates c++11 typedef typename


【解决方案1】:

输入f的实际类型即可:

typedef functor<T, T(*)()> F;

或者你可以使用decltype:

typedef functor<T, decltype(f)> F;

或者你可以为这样的东西写一个别名:

template <typename T>
using ReturnT = T(*)();

template <typename T>
int foo(ReturnT<T> f) {
    using F = functor<T, ReturnT<T>>;
    // ...
}

【讨论】:

    猜你喜欢
    • 2010-10-13
    • 1970-01-01
    • 2011-05-24
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多