views:

137

answers:

4

Hi

I got over a problem, I think a very specific one.

I've got 2 classes, a B aseclass and a D erived class (from B aseclass). B is a template class ( or class template) and has a pure virtual method virtual void work(const T &dummy) = 0; The D erived class is supposed to reimplement this, but as D is Derived from B rather than D being another template class, the compiler spits at me that virtual functions and templates don't work at once.

Any ideas how to accomplish what I want?

I am thankfull for any thoughts and Ideas, especially if you allready worked out that problem

this class is fixed aka AS IS, I can not edit this without breaking existing code base

template <typename T>
class B {
public:
...
virtual void work(const T &dummy) = 0;
..
};

take int* as an example

class D : public B<int*>{
...
virtual void work(const int* &dummy){ /* put work code here */ }
..
};

Edit: The compiler tells me, that void B<T>::work(const T&) [with T = int*] is pure virtual within D

+6  A: 

You placed the const in the wrong place. Try

virtual void work(int* const &dummy){ /* put work code here */ }

const int* is the same as int const*, i.e. it associates the const with the int and not the pointer.

Rüdiger Hanke
+1  A: 

Try:

int* const& dummy
Does this really matter, I mean I did it like above since I learned C++ and nobody complained so far... so far... Is there some documentation and best practice for const?
penguinpower
It's the difference between "const pointer to a int" and "a pointer to a const int"
Douglas Leeder
A: 

Which compiler?

g++ 4.4 didn't complain about:

template <typename T>
class B {
public:
virtual void work(const T &dummy) = 0;
};
class D : public B<int*>{
virtual void work(const int* &dummy){ /* put work code here */ }
};

int main(){return 0;}

EDIT: Of course - the error only showed up when actually instantiating D, fixed by moving the const keyword:

template <typename T>
class B {
public:
virtual void work(const T &dummy) = 0;
};
class D : public B<int*>{
virtual void work(int* const &dummy){ /* put work code here */ }
};

int main(){D d;return 0;}
Douglas Leeder
g++ (GCC) 4.4.3 20100127 (Red Hat 4.4.3-4)and I think it was the qt preprocessor being the guilty one
penguinpower
@Douglas Because you didn't use the templates.
anon
A: 

You have a mixture of const and reference problems. The following compiles:

template <typename T>
struct B {
virtual void work(T dummy) = 0;
};

struct D : public B<int*>{
virtual void work( int* dummy){ /* put work code here */ }
};

int main() {
    D d;
    d.work( 0 );
}
anon
Are const references to pointers bad practice or forbidden? Nvm, got it.
penguinpower