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

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

本文关键字:定义 使用 C++11 参数 类型 变参 用于      更新时间:2023-10-16

我刚刚定义了 4 种差异最小的不同 typedef,我想知道是否有办法使用模板更有效地做到这一点。

我的 typedef 的形式是:typedef Type1 (*pf)(Type2, Type3, ...)

如何模板化此类型定义?

只需要Type1

我手动写:

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

我正在寻找类似的东西:

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

这是对的吗?

是的,当然,两行(可能是单行,具体取决于您的代码风格(:

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

这采用了一种称为alias template的技术 http://en.cppreference.com/w/cpp/language/type_alias:

别名模板类似于类模板,因为它不定义新类型

(如类型别名(,而是定义用于定义新类型的模板。当与不同的类型一起使用时,它会基于此模板提供类型定义。这是C++11功能。

您可以通过推迟

到专门用于函数签名的模板类来创建易于阅读的函数指针类型def:

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