Specifying the template parameter for lambda in C++20

Viewed 49

I am implementing some kind of a visit on my class where users will provide polymorphic lambda and I will do dispatching based on runtime index. Simple silly example is this:

#include <iostream>

template<typename F>
void visit(F f){
    if(rand()%2){
        f(47);
    } else {
        f(4.7);
    }
}

int main()
{
    visit([]<typename T>(const T& ){std::cout << sizeof(T);});
    visit([]<typename T>(const T& ){std::cout << sizeof(T);});
    visit([]<typename T>(const T& ){std::cout << sizeof(T);});
    visit([]<typename T>(const T& ){std::cout << sizeof(T);});
    visit([]<typename T>(const T& ){std::cout << sizeof(T);});
    visit([]<typename T>(const T& ){std::cout << sizeof(T);});
    visit([]<typename T>(const T& ){std::cout << sizeof(T);});
};

This works but if lambda only cares about the type of argument and not it's value it requires lambda to take 1 useless argument.

Is there a way I could rewrite this code so that I tell lambda what T it is being called with, and having callback arity 0?

Obvious attempt (f<int>, f<double>) does not work.

This works but it is quite ugly, is there a nicer way?

void visit(F f){
    if(rand()%2){
        f.template operator()<int>();
    } else {
        f.template operator()<double>();
    }
}
0 Answers
Related