Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a pointer type as a template parameter

The following code

#include <iostream>

template<typename T>
class Abstract
{
public:
    virtual ~Abstract()
    {}
    virtual void func(const T &param) const = 0;
};

class Concrete : public Abstract<int*>
{
public:
    virtual void func(const int *&param) const override  // watch out!
    {}
};

int main()
{
    Concrete c;
}

produces the following compile error at the line marked with the comment:

error C3668: 'Concrete::func' : method with override specifier 'override' did not override any base class methods

If I remove the override, this error will be shown:

error C2259: 'Concrete' : cannot instantiate abstract class

How to derive from Abstract<int*>?

like image 865
TobiMcNamobi Avatar asked Apr 21 '26 04:04

TobiMcNamobi


1 Answers

Declare Concrete like this:

class Concrete : public Abstract<int*>
{
public:
    virtual void func(int * const &param) const override
    {}
};

The question is: Which part of the parameter of Abstract<int*>::f() is const?

The answer: Since T is const and T in Abstract<int*> is a pointer (to an int), it is the pointer that is const - not the int.

like image 105
TobiMcNamobi Avatar answered Apr 22 '26 20:04

TobiMcNamobi



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!