【问题标题】:Using std::result_of<> for member method of member type对成员类型的成员方法使用 std::result_of<>
【发布时间】:2018-04-27 18:20:38
【问题描述】:

我正在使用一个 HashMap 类型,它没有将其 KeyType 指定为公共成员,只有 ValueType。检索 KeyType 的一种方法是将std::result_ofHashMap&lt;&gt;::Entry::GetKey() 方法一起使用。我无法让它在模板中工作。

template <typename K, typename V>
class Map {
public:
  using ValueType = V;
  class Entry {
  public:
    K GetKey();
  };
};

这很好用:

using M = Map<int, float>;
using T = std::result_of<decltype(&M::Entry::GetKey)(M::Entry)>::type;
static_assert(std::is_same<T, int>::value, "T is not int");

但是我将如何从M 是模板类型参数的模板中做到这一点?我尝试使用上述方法并插入 typename 关键字,但没有成功。

template <typename M>
struct GetKeyType {
  using T = std::result_of<decltype(&(typename M::Entry)::GetKey)(typename M::Entry)>::type;    
};

using T = GetKeyType<Map<int, float>>::T;
static_assert(std::is_same<T, int>::value, "T is not R");

【问题讨论】:

    标签: c++ templates typename result-of


    【解决方案1】:

    &amp;M::Entry::GetKey 是一个整体,你不应该用typename 将它们分开。

    以下代码将起作用:

    template <typename M>
    struct GetKeyType {
      using T = typename std::result_of<decltype(&M::Entry::GetKey)(typename M::Entry)>::type;
    };
    

    【讨论】:

    • 那一定是我没试过的唯一版本。 :^) 为什么它按原样接受&amp;M::Entry::GetKeyM::Entry不是需要通过typename访问的依赖类型吗?
    • @NiklasR 被查找的名称是GetKeytypename 只有当实际被查找的名称是一个类型时才使用消歧器,这里不是这种情况。 M::Entry::GetKey是一个限定名,是一个整体,不能简单的拆成碎片。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2018-02-01
    相关资源
    最近更新 更多