Skip to content

Instantly share code, notes, and snippets.

@admo
Created April 8, 2019 07:08
Show Gist options
  • Save admo/e701955778792ce9a9e9f02093447ea7 to your computer and use it in GitHub Desktop.
Save admo/e701955778792ce9a9e9f02093447ea7 to your computer and use it in GitHub Desktop.
WTK: C++

Wrap function with template with pointer argument

The general idea can be found here. The idea is to write a template which wraps function. Template takes as an argument pointer to the function.

Until C++17

Implementation:

#include <utility>

template <class F, F f> struct wrapper;

template <class R, class... Args, R (*f)(Args...)>
struct wrapper<R (*)(Args...), f> {
  static R call(Args... args) {
    // ...
    return f(args...)
  }
};

Usage:

int foo(int);

auto bar(int n) {
    return wrapper<decltype(&foo), &foo>::call(n);
}

Example.

Since C++17

Implementation:

#include <utility>

template <auto f> struct wrapper;

template <class R, class... Args, R (*f)(Args...)>
struct wrapper<f> {
  static R call(Args... args) {
    // ...
    return f(args...);
  }
};

Usage:

int foo(int);

auto bar(int n) {
    return wrapper<foo>::call(n);
}

Example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment