Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use return type and parameter type of function as template types [duplicate]

Is it possible to figure out the return type and parameter type of a function and use them as template types? Consider the following example:

template <typename ret, typename in>
class Bar {
  // Some code
}

int foo(float x) {
  return 0;
}

int main() {
  Bar<int, float> b; // Can this be done automatically by inspection of foo at compile time?
}

Can I use the function signature of foo to set the template types of Bar?

like image 848
Gizmo Avatar asked Jan 27 '26 17:01

Gizmo


1 Answers

Yessir.

template <class Function>
struct BarFor_;

template <class Ret, class In>
struct BarFor_<Ret(*)(In)> {
    using type = Bar<Ret, In>;
};

template <auto function>
using BarFor = typename BarFor_<decltype(function)>::type;

Now you can get your type via:

 BarFor<foo> b;

See it live on Coliru

like image 72
Quentin Avatar answered Jan 29 '26 07:01

Quentin



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!