r/cpp • • Mar 17 '26

Easy Virtual Template Function. C++26

Have you ever wanted to use virtual template functions but found existing methods have so much boilerplate? Ever thought that virtual template functions could be done without it? Well, with the new reflection features, it can be!

The main goal was to minimize the amount of code required to use virtual template functions. This has been accomplished. Each base class needs to inherit only one class, and each base virtual template function requires one line of code to provide the minimal information required. This looks a lot nicer as it is very similar to how normal virtual functions are created.

Simple example:

struct D1;
struct D2;

struct Base: VTF::enable_virtual_template_functions<D1,D2>{
    template<typename T>
    Base(T* ptr): enable_virtual_template_functions(ptr){}

    template<typename T>
    int f(int a){
        constexpr auto default_function = [](Base* ptr, int a){ return 99;};
        CALL_VIRTUAL_TEMPLATE_FUNCTION(^^T,default_function,a);
    }
};

struct D1:Base{
    D1():Base(this){}

    template<typename T>
    int f(int a){
        return 11;
    }
};

struct D2:Base{
    D2():Base(this){}

    template<typename T>
    int f(int a){
        return 12;
    }
};

int main(){
    using PtrT = std::unique_ptr<Base>;
    PtrT a = std::make_unique<D1>();
    PtrT b = std::make_unique<D2>();
    assert((a->f<int>(1) == 11));
    assert((b->f<int>(1) == 12));
}

Godbolt link

12 Upvotes

12 comments sorted by

View all comments

Show parent comment

2

u/Top-Mycologist-5460 Mar 19 '26

Great, thanks for the explanation! Why must CALL_VIRTUAL_TEMPLATE_FUNCTION be a macro?

1

u/Reflection_is_great Mar 19 '26

CALL_VIRTUAL_TEMPLATE_FUNCTION hides some automation code to retrieve the identifier and return type of the function it is called inside, and to wrap the template parameters and function parameter types into the required internal template types. It could be written manually, but it would be lengthy and somewhat unappealing. Fun fact: the reason the macro requires you to provide the template and function parameters is that I couldn't find a way to automate them. I could’ve automated the function parameters, but that would have made it impossible to overload the virtual function templates.