Goodies
Goodies

Reputation: 4681

Extract a typedef/using definition from a template class

Is there a way to extract a typedef from a template class? For example, this is what I would like to do:

template<typename T, typename... Args>
class Foo{
public:
   typedef T(*Functor)(Args...);
   Foo() = default;
};

template<typename T, typename... Args>
Foo<T, Args...> make_foo(T(*f)(Args...)){
    return Foo<T, Args...>;
}

int bar(int i){
    return i * 2;
}

using type = make_foo(bar)::Functor;

I cannot do this. However, I can do this:

using type = Foo<int, int>::Functor;

This sort of defeats the purpose for me. Is there any way to wrap a function such that I can extract it in type form?

Upvotes: 1

Views: 54

Answers (2)

rems4e
rems4e

Reputation: 3172

Use decltype:

template<typename T, typename... Args>
class Foo{
public:
   typedef T(*Functor)(Args...);
   Foo() = default;
};

template<typename T, typename... Args>
Foo<T, Args...> make_foo(T(*f)(Args...)){
    return Foo<T, Args...>{}; // Small compilation error fixed here.
}

int bar(int i){
    return i * 2;
}

using type = decltype(make_foo(bar))::Functor;

This operator returns the type of the expression it is fed with.

Upvotes: 4

jrok
jrok

Reputation: 55395

Would decltype be good enough?

using type = decltype(make_foo(bar))::Functor;

Upvotes: 5

Related Questions