Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functions as template arguments

I have a TaskWrapper:

template <typename T, T (*F)(T)>
struct TaskWrapper {
  static inline T run(T clock) {
    return F(clock);
  }
};

to use it I have to specify the T template argument:

uint16_t task1(uint16_t clock) { return clock + 1; }
typedef tasks::TaskWrapper<uint16_t, task1> Task;

I would like to simply write:

typedef tasks::TaskWrapper<task1> Task;

and let the compiler figure out that the return and argument type is uint16_t.

Notes:

The TaskWrapper is obviously simplified and in reality has a few other arguments, which are passed during the typedef.

The wrapped functions can only be:

uint8_t task(uint8_t clock);
uint16_t task(uint16_t clock); // or
uint32_t task(uint32_t clock);

The TaskWrapper is passed as template argument to another class, which will at some point call Task::run(...);

C++11 would be fine.

like image 344
close2 Avatar asked Dec 10 '25 19:12

close2


1 Answers

Only since C++17's template <auto> feature:

template <auto F>
struct TaskWrapper {
  template <typename T>
  static inline auto run(T clock) {
    return F(clock);
  }
};

uint16_t task1(uint16_t clock) { return clock + 1; }
typedef TaskWrapper<&task1> Task; // ok
like image 152
yuri kilochek Avatar answered Dec 12 '25 08:12

yuri kilochek



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!