0

I was having an issue with std::is_base_of being called inside of a class declaration for an incomplete type. I came across this StackOverflow question: Why can't "is_base_of" be used inside a class declaration (incomplete type)?

Then I tried to implement my own metafunction for checking if the given template class is base of another.

I have tested my code with C++17 on MSVC 19.28.29337 (version reported by cl.exe) and on clang-7 online compiler, and seems it works perfectly both for complete and incomplete classes. Here is my code:

namespace helper {
    template<class Base>
    static std::true_type isBaseOf(Base *b);

    template<class Base>
    static std::false_type isBaseOf(...);

    template<class Base>
    static std::false_type isBaseOf(void*);
}

template<class B, class D>
using IsBaseOf = decltype(helper::isBaseOf<B>(std::declval<D*>()));

template<class B, class D>
static inline constexpr bool IsBaseOf_v = IsBaseOf<B, D>::value;

Now I am wondering, what is wrong with my code? Isn't it portable? Doesn't it conform to the standard? Have I done something unacceptable?

Also, if everything is ok with my code, then why is the standard not using such a simple implementation?

Edited

Added handling for void type - thanks to Scheff.

Rub
  • 160
  • 2
  • 12
  • 1
    Your approach has a flaw: It claims that `void` is a base class: [**Demo on coliru**](http://coliru.stacked-crooked.com/a/486843c2877309fc) – Scheff's Cat Feb 17 '21 at 06:16
  • 2
    It also doesn't handle non-public inheritance. – Axalo Feb 17 '21 at 06:22
  • 1
    All code you ask about needs to be posted **inline** in the question. A link to an online compiler is nice to have, but it mustn't be required to follow it to get an understanding of your question. Links go stale, or may be inaccessible. The network I'm on won't let me load your Repl.it snippet for instance. – StoryTeller - Unslander Monica Feb 17 '21 at 08:37
  • @StoryTeller-UnslanderMonica Actually I have inlined all the required code. The links are optional. – Rub Feb 17 '21 at 08:46
  • Thanks, @Axalo. I will be waiting for other answers. If no one answers then your point seems to be the only difference. – Rub Feb 17 '21 at 08:49
  • 1
    You most certainly did not. How did you determine "it works"? I see no code that tests that. What if the answer is "your test is flawed"? – StoryTeller - Unslander Monica Feb 17 '21 at 08:56
  • @StoryTeller-UnslanderMonica Yeah, I know that my test may be flawed, that's why I said 'seems it works' and my question is: **what is wrong with my code.** :) I am asking you to help me to find the flaws in the code I provided in my question. And the links are **optional** there is no need to inline them. Please read the question before making comments :) – Rub Feb 17 '21 at 09:37

1 Answers1

0

Seems the only difference is that it does not handle non-public inheritance.
Thanks to Axalo for the comment

Rub
  • 160
  • 2
  • 12