Derived template-class access to base-class member-data

前端 未结 3 705
天涯浪人
天涯浪人 2020-11-22 00:45

This question is a furtherance of the one asked in this thread.

Using the following class definitions:

template 
class Foo {

public:
         


        
3条回答
  •  清歌不尽
    2020-11-22 01:07

    Appears to work fine in Visual C++ 2008. I've added some dummy definitions for the types you mentioned but gave no source for. The rest is exactly as you put it. Then a main function to force BarFunc to be instantiated and called.

    #include 
    
    class streamable {};
    std::ostream &operator<<(std::ostream &os, streamable &s) { return os; }
    
    class foo_arg_t : public streamable {};
    class a_arg_t : public streamable {};
    class b_arg_t : public streamable  {};
    
    template 
    class Foo {
    
    public:
        Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg)
        {
            /* do something for foo */
        }
        T Foo_T;        // either a TypeA or a TypeB - TBD
        foo_arg_t _foo_arg;
    };
    
    template 
    class Bar : public Foo {
    public:
        Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
        : Foo(bar_arg)   // base-class initializer
        {
    
            Foo::Foo_T = T(a_arg);
        }
    
        Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
        : Foo(bar_arg)
        {
            Foo::Foo_T = T(b_arg);
        }
    
        void BarFunc ();
    
    };
    
    template 
    void Bar::BarFunc () {
        std::cout << _foo_arg << std::endl; 
        std::cout << Bar::_foo_arg << std::endl;   
    }
    
    int main()
    {
        Bar *b = new Bar(foo_arg_t(), a_arg_t());
        b->BarFunc();
    }
    

提交回复
热议问题