What would a CRTP-based solution to this look like?

前端 未结 2 778
南笙
南笙 2020-12-22 01:49

I asked the following question in this post (pasted below for convenience). One of the comments suggested that there is a CRTP-based solution to the problem. I am not able t

2条回答
  •  时光说笑
    2020-12-22 02:27

    to know whether a class derives from a base class we have the std::is_base_of<> template structure, which can be used in conjunction with partial specialisation, or std::enable_if.

    Here is a demonstration of using a partially specialised structure to apply a an operation depending on whether it's derived from node_base or not (in this case, it just prints the base object but you could do any other operation)

    #include 
    #include 
    
    // base class
    struct node_base
    {
    
    };
    
    std::ostream& operator<<(std::ostream& os, const node_base& nb)
    {
        os << "node_base_stuff";
        return os;
    }
    
    // a class derived from node_base
    struct node : public node_base
    {
    
    };
    
    // a class not derived from node_base    
    struct not_node
    {
    
    };
    
    // apply the general case - do nothing
    template
    struct report_impl
    {
        static void apply(const T&) {};
    };
    
    // apply the case where an object T is derived from node_base    
    template
    struct report_impl::value > >
    {
        static void apply(const T& t) {
            std::cout << static_cast(t) << std::endl;
        };
    };
    
    // the general form of the report function defers to the partially
    // specialised application class
    template
    void report(const T& t)
    {
        report_impl::apply(t);
    }
    
    using namespace std;
    
    // a quick test    
    auto main() -> int
    {
        node n;
        not_node nn;
        report(n);
        report(nn);
    
        return 0;
    }
    

    expected output:

    node_base_stuff
    

提交回复
热议问题