does it makes sense a virtual template method?
Asked Answered
S

3

5

Suppose a construct like this:

class Interface
{
public:
   template <typename T>
   virtual void reportOperationError(T code , std::string message) = 0;
};

i don't understand the use case for this thing, in which case it is useful, and how?

In case you wonder, I haven't seen this code anywhere, just want to understand if this could have some particular use

Sedda answered 10/7, 2011 at 15:13 Comment(0)
L
6

Templated member functions cannot be virtual... Each instantiation of the function will add another entry to the virtual table, and the compiler will have to go over all of the code in order to create the vtable. Therefore, regardless of it being useful or not, it's just not legal C++.

Lemonade answered 10/7, 2011 at 15:15 Comment(0)
S
3

This isn't legal in C++. Member function templates cannot be virtual because the size of the VTable would be dependent on instantiations in other translation units which would make it very very hard for compiler implementers.

This would ruin the whole point of C++ compilation model, that is, separate compilation. A C++ translation Unit (AKA source file) must be self-sufficient to be compiled. If the member function tamplates are allowed, this gets nearly impossible

Supermarket answered 10/7, 2011 at 15:16 Comment(0)
S
0

It's not possible to make virtual member function a template. This code will not compile, regardless of its potential utility.

Spatter answered 10/7, 2011 at 15:15 Comment(1)
Yep. Interestingly, while template compilation errors are usually quite inscrutable, the error message generated by gcc when it confronts the above code is crystal clear: error: templates may not be 'virtual'.Calamondin

© 2022 - 2024 — McMap. All rights reserved.