Search code examples
c++templatestypenameresult-of

Using std::result_of<> for member method of member type


I am working with a HashMap type that does not specify its KeyType as a public member, only the ValueType. A way to retrieve the KeyType would be to use std::result_of with the HashMap<>::Entry::GetKey() method. I can't get it to work in a template though.

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

This works fine:

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");

But how would I do it from a template where M is a template type parameter? I have tried to use the above and insert typename keywords with no success.

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");

Solution

  • &M::Entry::GetKey is a whole, you should not separate them by a typename.

    The following code will work:

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