如何在具有约束的函数中使用泛型(C ++)

时间:2019-09-29 19:03:47

标签: c++

我有一种算法,需要使用父级“ Stack”(即“ LinkedStack”,“ ArrayStack”等)的许多实现来执行。 我发现,如果将此算法编写到函数中并提供某种通用的键入/模板函数魔术,则可以解决此问题。

但是我没有找到任何办法。

我已经搜索并尝试了许多语法,但也许只是不可能?

template<class T: Stack> // Imaginary synthax to tell "T is a Stack"
void doTaskWithSpecificImplementation() 
{
    // Eventually somewhere in the function:
    T stack = new T();
}

void main() {
    doTaskWithSpecificImplementation<LinkedStack>();
}

我希望这段代码在规定使用特定的虚拟类实现的同时,提供一种简单快捷的方法来调用函数。

1 个答案:

答案 0 :(得分:0)

您的问题不涉及重载,而只是在您输入错误的类型时给出可理解的错误。在这种情况下,static_assertstd::is_base_of

template<typename T>
void doTaskWithSpecificImplementation() {
    static_assert(std::is_base_of<Stack, T>{}, "T must be a Stack or a Stack subclass");
}