5

Let's say I have a function that takes two different templated arguments:

template<typename T, typename U>
void fun(T t, U u);

Types T and U are part of the same inheritance tree. I'd like to get the most specific class that they both inherit from.

typedef /*something*/ shared_parent;

For example, if type T and type U are the same type, I want that type. If type T inherits from type U, I want type U. If Type T and type U both inherit from the same parent, I want that parent.

If types T and U are not part of the same inheritance tree, I don't care what happens.

IanPudney
  • 5,941
  • 1
  • 24
  • 39
  • 1
    I would've thought that [`std::common_type`](http://en.cppreference.com/w/cpp/types/common_type) would've worked, but ti was designed for something else – Justin Jul 14 '17 at 18:51
  • 2
    Since C++ supports multiple inheritance, I don't think it is possible to get "that same parent" from template magic. This post might help you : https://stackoverflow.com/a/16262354/2950563 – Jérémi Panneton Jul 14 '17 at 18:51
  • You're correct that std::common_type is something different, but it actually works for my purposes. – IanPudney Jul 14 '17 at 19:02
  • There's no way to do it in present C++. If reflection gets added to the language eventually then you'll be able to write a custom trait that walks up the inheritance trees manually. – Brian Bi Jul 14 '17 at 19:05
  • @brian what's wrong with std::common_type? – xaxxon Jul 14 '17 at 19:06
  • @xaxxon it doesn't do this :) – Brian Bi Jul 14 '17 at 19:06
  • @Brian it seems like it does at least in some situations: https://godbolt.org/g/nAXPNJ – xaxxon Jul 14 '17 at 19:11
  • 2
    @xaxxon only when one of the types is a direct ancestor of the other – Brian Bi Jul 14 '17 at 19:11
  • @Brian I see. Thank you. https://godbolt.org/g/DxpUxS – xaxxon Jul 14 '17 at 19:16
  • GCC can do this if `std::tr2::bases` is employed. But AFAICS there's no standard-conforming approach. – Columbo Jul 15 '17 at 23:10

0 Answers0