c++ template problem

2019-02-27 17:13发布

问题:

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

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

and i have another class which method get all kind of these class through the arguments, and want to store the pointer in an array. The class dont want to access the specific (tempalted) parts of the classes only the common attributes/methods.

class Container {
    public: //of course public...
    MyClass* array; //this is allocated with some magic.
    void bar(MyClass& m) {
      and want to store the class in a MyClass* array.
    }
}

here is the error that argument list for template missing

how can i solve this?

回答1:

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
    }
};


回答2:

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) {
        /* ... */
    }
};


回答3:

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.



回答4:

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