Virtual Templates

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
 
struct Base
{
    virtual ~Base(){}
    
    template<typename T>
    virtual bool f(T t){ return false; }
};
struct Derived : Base
{
    virtual ~Derived(){}
 
    template<typename T>
    virtual bool f(T t) override { return false; }
    template<>
    virtual bool f<int>(int t) override { return true; }
};
 
int main()
{
    Base *b = new Derived();
    if(b->f(0))
    {
        std::cout << "It works" << std::endl;
    }
    else if(b->f<int>(0))
    {
        std::cout << "It sort of works" << std::endl;
    }
    else
    {
        std::cout << "It doesn't work" << std::endl;
    }
    delete b;
}
Conceptually, this should work, but the standard forbids it and the common vtable implementation makes it impractical.

What is a good alternative that still has the same characteristics? It can't be simple function overloading because you would have to modify the base class for every new overload introduced in derived classes.
> What is a good alternative that still has the same characteristics?

CRTP?
That won't work because even if the templated class inherited from a base class, you still couldn't perform a templated virtual function call from that base class.
What are you trying to say? This?

Start of loop:

Step 1: I know that a templated virtual function call is not allowed, and I also know why it is not allowed.

Step2: What is a good alternative that still has the same characteristics?

Step 3: An alternative for polymorphic behaviour, with characteristics akin to an overridden virtual function call.

Step 4: That is still not a templated virtual function call from that base class.

Step 5: Unconditionally go back to Start of loop.

And during every iteration, restate twice (once at the beginning and once more at the end):
A templated virtual function is not allowed.




Wow, what did I do to trigger such a reaction? I wasn't trying to be rude to you or anything, I was just explaining why your proposed solution doesn't have the same functionality.

I have figured it out, however - I can use a map to map types (std::type_index) to the correct function to call. It's a bit complex but it allows the same interface as if there actually were virtual templates.
Topic archived. No new replies allowed.