I have this interface:
struct I
{
virtual void f(int) = 0;
virtual void f(float) = 0;
};
May I implemnt I
using something similar to next class?
struct C : public I
{
template<typename T>
void f(T);
};
No, you can't do that. The template method overloads the original two methods (ie it's a different method with the same name). C
still has two pure virtual functions.
As properly pointed out by NPE, you can't do this directly. However, you still can avoid code duplication by delegation:
struct C : public I
{
void f(int x) { f_internal(x); }
void f(float x) { f_internal(x); }
private:
template<typename T>
void f_internal(T x) { do stuff with x; }
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.