user1899020
user1899020

Reputation: 13575

Is it possible to use using for functions?

For example

template<class T, class U>
void f();

template<class T> using g = f<T, int>;

Or any similar idea for functions?

Upvotes: 5

Views: 295

Answers (2)

Felix Glas
Felix Glas

Reputation: 15534

No, you can not do that as templated aliases are used to create aliases of types, not concrete data.

What you are trying to do is to create an alias/type from the address of a function as f<T, int> decays into a pointer to function.

You can however create a templated alias from the type of the function f.

template <typename T>
using g = typename std::add_pointer<decltype(f<T, int>)>::type;

int main() {
    // Type of 'func' is 'void (*)()' with template arguments '{T1=double, T2=int}'.
    g<double> func;

    func = f<double, int>; // Point to function with same signature and template args.
    func();                // Ok to call function.
}

Upvotes: 2

user1804599
user1804599

Reputation:

No. You cannot do that. You need to create a new function that calls f, forwarding all arguments and template arguments.

template<class T, class U>
void f();

template<class T>
void g() {
    f<T, int>();
}

A C++14 alternative is a variable template of function pointer type:

template<typename T>
void (*g)() = &f<T, int>;

Although this approach ignores default arguments and probably has other quirks as well. I highly recommend the more verbose wrapping approach.

Upvotes: 9

Related Questions