Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deduce second parameter type from first parameter?

I am new to template-metaprogramming. The second parameter will be the same as the function parameter passed. I want to deduce the second parameter type from Func.

template<typename Func>
void execute(Func func, decltype(Func) t) 
{
    std::cout << func(t) << std::endl;
}

int main() 
{
    std::function<int(float)> func1 = [](float f) { return int(f); };
    execute(func1,1.5);
    return 0;
}

This works, but I don't want to declare additional typenameme T since the info is already available in Func, so why not deduce.

template<typename Func, typename T>
void execute(Func func, T t) 
{
    std::cout << func(t) << std::endl;
}
like image 680
ark1974 Avatar asked Feb 18 '26 01:02

ark1974


1 Answers

I want to deduce the second parameter type from Func

I don't want to declare additional typename T

I do not see any simple solution to your requirement, other than passing the callable object to the function, after binding with the argument.

Following will make sure your second requirement and not need change your original code that much.

#include <functional>
#include <iostream>

template<typename Func>
void execute(Func func) {
    std::cout << func() << std::endl;
}
int main() 
{
    auto func1 = std::bind([](float f) { return int(f); }, 2.5f);
    execute(func1);
    return 0;
}
like image 190
JeJo Avatar answered Feb 20 '26 13:02

JeJo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!