如何在模板参数上执行合同

时间:2020-09-02 03:49:37

标签: c++ templates

如何指定模板参数为某种类型,即它必须已经实现了一个接口(模板参数必须是特定基类的派生类)

这里有接口​​(抽象基类)

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类。

1 个答案:

答案 0 :(得分:2)

是的,您可以使用std::is_base_of来检查类型,例如

template <class counterType, std::enable_if_t<std::is_base_of_v<baseActionCounter, counterType>>* = nullptr>
class bigBoss {

template <class counterType>
class bigBoss {
    static_assert(std::is_base_of_v<baseActionCounter, counterType>, "counterType must derive from baseActionCounter");
    ...
};

或使用concept(自C ++ 20起)。

template <class T>
concept Derived = std::is_base_of_v<baseActionCounter, T>;

template <Derived counterType>
class bigBoss {

BTW:如果指定了基类std::is_base_oftrue也会返回baseActionCounter;如果这不是您想要的,则可以将条件与std::is_same组合。

相关问题