template<typename T>
class A{
public:
virtualvoid fun(const T&) = 0;
};
class B : public A<int*>{
public:
// Doesn't compile
void fun(constint*& i){
constint j = *i;
}
};
int main(){
B b;
constint* k = newint(44);
b.fun(k);
return 0;
}
Hi, the code above won't compile. The problem is that the compilers don't accept B::fun as overrider. Has anyone a suggestion how the parameter list of B::fun has to look like?
I think what you need is template specialisation. Instead of declaring the second virtual function, you just need to declare an implementation of A<int*>.
Thanks for your reply kbw! I removed the second virtual function. It was only for explaination that a parameter like const int*& works in principle. I'm not sure what is meant by "declare an implementation of A<int*>".
I tried it with class template specialisation but it the example below doesn't compile. I think I haven't completely understood how template specialisation works.
Please read my post above. You will never be able to call fun() as a virtual method. You cannot have virtual template functions (which is essentially what you have since it takes a templated type as a parameter, even though the template is on the class, not the function).
Hi anders43, thanks, but I found this solution as well.
It works also if the specification is virtualvoid fun(T t) = 0;
(just leaving the const ant the &). This is what I use as workaround for my problem. It works fine. But I don't see a reason why the example I posted initially shouldn't work. If it were no pure virtual function void fun(const T& t) with T = const AClass*, that works too.
I found the solution to my problem! The point in my initially posted example is that the const bound to the int in the parameter list in the fun definition (line 10), I think. And the const in line 17 is wrong.
Here an example which compiles.
But I still don't know what strange things can occur doing so. Is it probably harmful to pass a pointer by reference?
That would do the same thing even if the virtual function in A is commented out. I'm not clear on what you're trying to do. There's no polymorphism at work here.
You're right, there is no polymorphism at work here. I wanted to find an overrider for fun in the derived classes. Because void fun(constint*& i) is no overrider if the actual template parameter is int*. I've found what I want. I think we can now stop the discussion here.
Thanks to all for the replies.