Usage of CRTP in a call chain

Posted by fhw72 on Stack Overflow See other posts from Stack Overflow or by fhw72
Published on 2012-12-18T10:55:06Z Indexed on 2012/12/18 11:03 UTC
Read the original article Hit count: 149

Filed under:
|
|

In my widget library I'd like to implement some kind of call chain to initialize a user supplied VIEW class which might(!) be derived from another class which adds some additional functionality like this:

#include <iostream>

template<typename VIEW>
struct App
{
    VIEW view;
    void init() {view.initialize(); }
};

template<typename DERIVED>
struct SpecializedView
{
    void initialize()
    {
        std::cout << "SpecializedView" << std::endl;
        static_cast<DERIVED*>(this)->initialize();
    }
};

struct UserView : SpecializedView<UserView>
{
    void initialize() {std::cout << "UserView" << std::endl; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    // Cannot be altered to: App<SpecializedView<UserView> > app;
    App<UserView> app; 
    app.init();
    return 0;
}

Is it possible to achieve some kind of call chain (if the user supplied VIEW class is derived from "SpecializedView") such that the output will be:

console output:

SpecializedView
UserView

Of course it would be easy to instantiate variable app with the type derived from but this code is hidden in the library and should not be alterable. In other words: The library code should only get the user derived type as parameter.

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates