0

I have an algorithm that needs to be executed with many implementations of a parent class named "Stack" (i.e. "LinkedStack", "ArrayStack", etc). I figured out that if I write this algorithm into a function and provide some sort of generic typing/template function magic, the problem would be solved.

But I didn't find any means to do so.

I've searched and tried many syntaxes but maybe it's just not possible?

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>();
}

I expect this code to provide a short and easy way to call a function while prescribing the use of specific virtual class implementation.

B. Bergeron
  • 90
  • 1
  • 10
  • I'm gonna infer that you're coming from java or similar where you can have `extends` on a generic type. Typically C++ uses more of a compile-time duck-typing approach (though this will shift with Concepts). – Ryan Haining Sep 29 '19 at 19:10
  • @MaxVollmer Indeed, it is. Thank you! – B. Bergeron Sep 29 '19 at 19:14

1 Answers1

0

Your question doesn't mention overloading, but simply giving a comprehensible error when you get the wrong type. In this case, static_assert with std::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");
}
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • sfinae would be a better solution: what if down the road we want a different impl if it's not a stack? – Cruz Jean Sep 29 '19 at 19:21
  • The static_assert is expedient, SFINAE makes for verbose and somewhat opaque compile time error messages. If it is a shared code base, SFINAE is probably the better choice. If it is entirely internal to a specific project, it's a judgement call. – Eljay Sep 29 '19 at 19:42