c++ template problem

前端 未结 4 1583
独厮守ぢ
独厮守ぢ 2021-01-25 20:00

i have a class which has a template by other purposes:

template
class MyClass {
    public: //of course public...
    t foo;
    std::string text;         


        
相关标签:
4条回答
  • 2021-01-25 20:37

    The simplest method would be to make that function a template as well:

    template <class t>
    void bar(MyClass<t>& m) {
        // ...
    }
    

    Note that that should probably be const MyClass<t>&, because you don't need to modify it.


    Your new code is meaningless. There is no such that as an object of type MyClass, because MyClass is a template. If you want to operate on these classes irrespective of their template argument, then you need to factor out the non-template portions as a base class:

    class MyClassBase
    {
    public:
        // polymorphic base classes should always have virtual destructors
        ~MyClassBase() {}
    
        virtual void some_function() = 0;
    };
    
    template <typename T>
    class MyClass : public MyClassBase
    {
    public:
        // implement abstract functions
        void some_function()
        {
            // template argument T is available here
        }
    };
    

    Then you can refer to that base, and when you call a virtual function it will dynamically dispatch:

    class Container
    {
    public:
        // no magic: use a std::vector for dynamic arrays
        std::vector<MyClassBase*> array; // not by value! avoid slicing
    
        void bar(MyClassBase& m)
        {
            array.push_back(&m);
        }
    
        void baz()
        {
            array[0]->some_function(); // for example
        }
    };
    
    0 讨论(0)
  • 2021-01-25 20:37

    the text variable in your class is private so unless you bar function is a method of the class you can't legally use it like that

    0 讨论(0)
  • 2021-01-25 20:49

    How about putting a common base class.

    class MyClassCommon {
    protected:
        ~MyClassCommon() { }
    
    public:
        std::string text;
    };
    
    template<class t>
    class MyClass : public MyClassCommon {
    public: // of course public...
        t foo;
    };
    
    class Container {
    public: // of course public...
        MyClassCommon* array; // this is allocated with some magic.
        void bar(MyClassCommon& m) {
            /* ... */
        }
    };
    
    0 讨论(0)
  • 2021-01-25 20:57

    If you want to create a "multi-template" array, you'd better use a non-template class as a base class of a template class. Or you can make a template array and store any objects in it.

    0 讨论(0)
提交回复
热议问题