lun
lun

Reputation: 33

Const keyword in template argument

I have the following C++ code:

template<typename T> class AbsClass{
public:
    virtual void func(const T elem) = 0;
};

class SolidClass : public AbsClass<char*>{
public:
    void func(const char* elem) {cout << elem << endl;}
};

int main(){
    SolidClass so;
    so.func("xyz");
}

However, when I try to instantiate an instance of SolidClass in main(), the compiler (g++ 4.8.1) keeps complaining the error that the pure virtual function AbsClass::func(const T elem) has not been implemented. It would work if I change the definition of SolidClass to the following:

class SolidClass : public AbsClass<const char*>{
    .......
}

I'm just confused since I already have the const keyword in declaring AbsClass::func(const T elem). Could anybody help explain the fact?

Upvotes: 3

Views: 200

Answers (3)

mpark
mpark

Reputation: 7894

Remember that const T == T const and it'll be easier to see that syntactic substitution doesn't yield the same result here. In this case subtituting char * in as T syntactically causes confusion since it may seem that const T is const char * and T const is char *const. In reality both const T and T const yields char *const.

static_assert(std::is_same<std::add_const_t<char *>, char *const>::value, "");

Upvotes: 1

Neil Kirk
Neil Kirk

Reputation: 21813

Pointers have two types of const. The first is whether you can modify the data they point to - this const means more of "read-only". The second const is whether the pointer itself is a constant value - that is whether you can make it point to something else. In this case, your pointer const char* can be changed to point to something else.

To make a pointer constant (so it cannot point to anything else) you must place a const after the *. So to get it to compile, your code should be:

void func(const char *const elem)

Assuming you still want the data it points to, to be read-only through this pointer. You will need to change the template parameter to AbsClass<const char*>

If the parameter is by value, I usually avoid making it a const. There is no point, as it is copied anyway, so any local changes by the function don't matter.

Upvotes: 1

Pradhan
Pradhan

Reputation: 16777

const char* is a pointer to a const char. You meant to say char * const.

Upvotes: 0

Related Questions