相关疑难解决方法(0)

C++类成员函数模板可以是虚拟的吗?

我听说C++类成员函数模板不能是虚拟的.这是真的?

如果它们可以是虚拟的,那么一个人可以使用这样一个函数的场景的例子是什么?

c++ templates virtual-functions c++-faq function-templates

293
推荐指数
8
解决办法
18万
查看次数

如何在C++中实现"虚拟模板功能"

首先:我已阅读并且我现在知道在C++中虚拟模板成员函数(但是?)是不可能的.解决方法是将类作为模板,然后在member-function中使用template-argument.

但是在OOP的上下文中,我发现如果该类实际上是一个模板,下面的例子将不会非常"自然".请注意,代码实际上不起作用,但gcc-4.3.4报告:error: templates may not be ‘virtual’

#include <iostream>
#include <vector>

class Animal {
    public:
        template< class AMOUNT >
        virtual void eat( AMOUNT amount ) const { 
            std::cout << "I eat like a generic Animal." << std::endl; 
        }
        virtual ~Animal() { 
        }
};

class Wolf : public Animal {
    public:
        template< class AMOUNT >
        void eat( AMOUNT amount) const { 
            std::cout << "I eat like a wolf!" << std::endl; 
        }
        virtual ~Wolf() { 
        }
};

class Fish : public …
Run Code Online (Sandbox Code Playgroud)

c++ virtual templates

41
推荐指数
5
解决办法
5万
查看次数