Mr.Anubis
Mr.Anubis

Reputation: 5322

Confusing Inheritance and templates

Here is the code I was looking, Source code :

template <typename T>
struct function_traits
    : public function_traits<decltype(&T::operator())>
{};

if we instantiate it with some functor X i.e function_traits<X>; , That will build the base class which is function_traits<decltype(&X::operator())> due to inheritance , but to build function_traits<decltype(&X::operator())> it's base also has to be built, which could be function_traits<decltype(Z)>

I understand function_traits<X> != function_traits<Z>. Isn't that recursive inheritance? 0_o. How all things is working together?

Upvotes: 1

Views: 152

Answers (1)

Peter Alexander
Peter Alexander

Reputation: 54270

This is illegal code. You cannot derive from an incomplete type, and at the point you try to derive from function_traits, the type is incomplete.

struct A { typedef A type; };
struct B { typedef A type; };

template <typename T>
struct X : X<typename T::type> {};

X<B> test; // error: invalid use of incomplete type ‘struct X<A>’

The only way you could get round this is if the function_traits you are trying to derive from is a complete type. You can do this using specialisation:

struct A { typedef A type; };
struct B { typedef A type; };

template <typename T>
struct X : X<typename T::type> {};

template <>
struct X<A> {}; // X<A> is now a complete type.

X<B> test; // OK! Derives from X<A>, which is complete.

Here, X<A> is complete when you try to derive from it, so you're fine.

Upvotes: 2

Related Questions