Variadic pattern for defining typedef (using C ++ 11)

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

My typedef looks like: typedef Type1 (*pf)(Type2, Type3, ...)

How do I customize this typedef?

Only required Type1

.

I manually write:

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

      

I am looking for something like:

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

      

Is it correct?

+1


source to share


2 answers


Yes, of course, two lines (could be one line depending on your code style):

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

      



In this case, a method is used which is called alias template

: http://en.cppreference.com/w/cpp/language/type_alias

An alias pattern is similar to a template pattern in the sense that it does not define a new type (for example, a type alias), but instead defines a pattern to define new types. When used with different types, it gives a type definition based on this template. This is a C ++ 11 feature.

+5


source


You can create an easy-to-read typedef function pointer by deferring a template class specialized 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;
}

      

+1


source







All Articles