mercredi 25 mai 2016

C++ use function argument type for template argument deduction

template<typename T>
void f(void (*func)(const T&)) {
    (*func)(T());
}

void func(const int& i) {
    std::cout << i << std::endl;
}

int main() {
    f(&func);
}

Here the template argument T (= int) of f is automatically deducted based on the first argument of the function func.

Can this also be extended to work with general functors (lambda functions or other function objects.) Possibly with a second function, i.e. something like

template<typename T, typename Function> f(Function func);

template<typename Function>
void call_f(Function func) {
    using arg_type = first_argument_type_t<Function>; // ???
    f<arg_type, Function>(function);
}

The fall to func in f should be able to be inlined by the compiler, so std::function cannot be used.

Aucun commentaire:

Enregistrer un commentaire