0

was reading book with solving different problems. And got next thing. There was a question, on how to check if class is derived from another one, using templates. And there was example on how to do this at compile time. I'm wodering why this code dont need definitions of static function.

template<typename T, typename B>
class CIsDerived
{
private:
    class CIsValid
    {
    };

    class CIsInValid
    {
        int sizeExp[3];
    };

    static CIsValid Check(B * pBaseClass);
    static CIsInValid Check(...);

public:
    enum
    {
        Is = sizeof(CIsValid) == sizeof(Check(static_cast<T*>(0)))
    };
};

class CBase
{
    public:
};

class CDerv : public CBase
{
public:

};

void main()
{
    cout << CIsDerived<CDerv, CBase>::Is << endl;
    cout << CIsDerived<string, CBase>::Is << endl;
}

Can someone provide any book, were this thing is explained in depth?

  • 1
    This code is based on meta-programming which happens at compile-time. So, implementations (needed at runtime) are not necessary. Have a look for a book about C++ template metaprogramming. Some of the books on the [C++ Booklist](https://stackoverflow.com/a/388282/7478597) might be suitable (especially what I saw in the **Intermediate** and **Advanced** section). – Scheff's Cat Jul 06 '19 at 08:11
  • 1
    You might also want to look up [SFINAE](https://en.cppreference.com/w/cpp/language/sfinae). – G.M. Jul 06 '19 at 08:22
  • 1
    Because the functions are never called. `sizeof` contains an unevaluated context. – Quimby Jul 06 '19 at 08:31
  • 1
    To extend @Quimby s comment: The code is using function _types_. To call a function, you would need an implementation. If you only need the function type (to operator on), the declaration is sufficient. – Scheff's Cat Jul 06 '19 at 09:49
  • They aren't odr-used. – L. F. Jul 06 '19 at 13:05
  • @Scheff ok cool got it, thanks for explanation will take a look to those books related to metaprogramming. Thanks a lot everyone. – Elvenemy Moth Jul 06 '19 at 16:18

0 Answers0