简体   繁体   English

用于定义typedef的可变参数模板(使用C ++ 11)

[英]Variadic template to define a typedef (using C++11)

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. 我刚刚定义了4个不同的typedef,它们之间的差异很小,我想知道是否存在使用模板的方法来更有效地执行此操作。

My typedef is of the form: typedef Type1 (*pf)(Type2, Type3, ...) 我的typedef的格式是: typedef Type1 (*pf)(Type2, Type3, ...)

How do I template this typedef? 如何为该typedef模板化?

Only Type1 is required. 仅需要Type1

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? 那是对的吗?

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的技术: 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. 这是C ++ 11的功能。

You can create an easy-to-read function pointer typedef by deferring to a template class specialised on the function signature: 您可以通过遵循专门针对函数签名的模板类来创建易于阅读的函数指针typedef:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM