Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper syntax in C++ for template classes with pointer template types with reference variables?

Tags:

c++

pointers

If I have a template class like this:

template <class T>
class MyClass
{
    public:
    virtual void MyFunction(const T& t)
    {
        ///
    }
};

How will MyFunction look like in a concrete class with a pointer T?

class Data;
class MyDerivedClass : public MyClass<Data*>
{
    public:
    void MyFunction(???) override
    {
        ///
    }
};

Also, how should I use the variable?

like image 718
Software Carpenter Avatar asked Oct 21 '25 11:10

Software Carpenter


2 Answers

If you really want this setup, you can.

Example:

class MyDerivedClass : public MyClass<Data*> {
public:
    using value_type = Data*;   // alias to simplify overriding

    void MyFunction(const value_type& dpr) override {
        // ....
    }
};

how should I use the variable?

You'd use it like any other pointer. Note that it's not the Data instance that is const, it's the pointer itself.

like image 105
Ted Lyngmo Avatar answered Oct 23 '25 01:10

Ted Lyngmo


You should try:

void MyFunction(Data * const & i) override

But also consider using the template instead of a derived class.

like image 44
fcatho Avatar answered Oct 23 '25 01:10

fcatho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!