Consider the following class:
template<typename T> class A{
public:
virtual void foo(const T& v){ m_v = v + 1; }
T& bar(){ return m_v;}
T m_v;
// ... other member functions/variables ...
};
How can it be modified such that the following code works (without, if possible having to to a const_cast
on p
):
int main(){
A<int*> a;
const int* p = nullptr;
a.foo(p);
a.bar();
A<int>().foo(10);
}
The problem is that the signature of the foo
method, when A
is templated by int*
becomes, as far as I can tell, foo(int* const&)
. What we would like to have would be something like foo(const int* const&)
.
Until now, I considered adding a specialized implementation of the foo
member function for A
templated by pointer types outside the class declaration (as one would do for specializing A<int>::foo
), but the compiler is not able to resolve the function definition prototype to the declared method.
template<typename T>
void A<T*>::foo(const T* const& ){}
gcc complains that it's an invalid use of incomplete type ‘class A<T*>’
I've also considered adding a partial specialization for the whole class for pointer types which defines an extra member overloading foo
that takes in a const T*
, but I couldn't figure out how to reuse the rest of the code in the base template (i.e. without duplicating the declarations and definitions for all the other functions, e.g. bar
). Is there a way to reference the base template class from the pointer partial specialization, either for inheritance or for having a member to which to forward calls? (This post provides a solution by adding an extra dummy template argument. Is there a way to circumvent this?).
Finally, I've also thought about using enable_if<is_pointer<T>::value, void>::type foo(const PointedToType*);
to add an extra overload to the foo
method when the template parameter is a pointer, but how can one get PointedToType
from T
(when it is known that T
is a pointer type)?