【发布时间】:2020-09-02 12:08:37
【问题描述】:
如何将模板参数指定为某种类型,即它必须已实现接口(模板参数必须是特定基类的派生类)
继承接口(抽象基类)
class baseActionCounter{
public:
virtual int eat()=0;
virtual int drink()=0;
};
现在我希望我的模板参数是 baseActionCounter 类型
这是模板类
//imaginary template syntax in the line below. Is there a way of achieving this behavior?
template <class counterType : baseActionCounter>
class bigBoss{
counterType counter;
public:
int consumerStats(){
//I am able to call member function because I know that counter object has eat() and drink()
//because it implemented baseActionCounter abstract class
return counter.eat() + counter.drink();
}
};
我也可以从 baseActionCounter 派生我的 bigBoss 类,但我想知道如何使用模板实现此行为。 此外,模板特化也不适合,因为对于 baseActionCounter 类的任何实现者只有一个 BigBoss 类。
【问题讨论】: