1

I have just defined 4 different typedefs with minimal differences and I'm wondering if there's way to use templates to do this more efficiently.

My typedef is of the form: typedef Type1 (*pf)(Type2, Type3, ...)

How do I template this typedef?

Only Type1 is required.

I manually write:

typedef int (*pf)(int)
typedef bool (*pf)()
typedef char (*pf)(bool, int)

I'm looking for something like:

template <Type T1,Type...Rest>
typedef T1 (*pf)(Type...Rest)

Is that correct?

Bob
  • 4,576
  • 7
  • 39
  • 107

2 Answers2

5

Yes, sure, two lines (could be single line depending on your code style):

template<class T, class... X>
using fptr_t = T (*)(X...);

This employs a technique which is called alias template: http://en.cppreference.com/w/cpp/language/type_alias

Alias template is akin to class template in a sense that it doesn't define new type (like type alias does), instead, it defines a template for defining new types. When used with different types, it gives you type definition based on this template. This is C++11 feature.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
2

You can create an easy-to-read function pointer typedef by deferring to a template class specialised on the function signature:

#include <iostream>


namespace detail {
    // define the template concept
    template<class Sig>
    struct function_ptr;

    // specialise on pointer to function of a given signature    
    template<class Ret, class...Args>
    struct function_ptr<Ret (Args...)>
    {
        using type = Ret (*)(Args...);
    };
}

// defer to template specialisation    
template<class Sig>
using function_ptr = typename detail::function_ptr<Sig>::type;

int test1(int) { return 0; }
bool test2() { return false; }
char test3(bool, int) { return 'a'; }

int main()
{

    using pfi = function_ptr <int (int)>;
    using pfv = function_ptr <bool ()>;
    using pfbi = function_ptr <char (bool, int)>;

    auto pt1 = pfi(test1);
    auto pt2 = pfv(test2);
    auto pt3 = pfbi(test3);

    std::cout << pt1(100) << std::endl;
    std::cout << pt2() << std::endl;
    std::cout << pt3(true, 100) << std::endl;
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142