开发者

virtual methods and template classes

开发者 https://www.devze.com 2022-12-24 04:03 出处:网络
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).

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


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.


Try:

int* const& dummy


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;}


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 );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号