简体   繁体   English

C ++可变数目的可变参数模板参数

[英]C++ Variable number of variadic template parameters

I have the following type alias: 我有以下类型别名:

using VoidFunc = void (*)();

I would like to define a class like so: 我想定义一个这样的类:

class SomeClass {
public:

 template<template<typename Return, typename... Args>... Funcs>
 static constexpr typename std::vector<VoidFunc> registerFunctions(Funcs<Return, Args...>... funcs) {
  return { ((VoidFunc)(funcs), ...) };
 }
};

I am aware that this is invalid syntax, as Return and Args are unresolvable outside of their template group. 我知道这是无效的语法,因为ReturnArgs在其模板组之外无法解析。 The goal is to allow the function registerFunction to accept a variable number of functions all with different prototypes. 目的是允许函数registerFunction接受数量可变的函数,这些函数都具有不同的原型。 In the actual implementation, it is important to preserve the type information of each function for use with other constexpr functions. 在实际的实现中,重要的是保留每个函数的类型信息以与其他constexpr函数一起使用。 Is there a way to achieve this in C++17 or later? 有没有办法在C ++ 17或更高版本中实现这一目标?

You don't actually care about any of those underlying types (at least not in the code presented here). 您实际上并不关心任何这些底层类型(至少不在此处显示的代码中)。 So just don't use it. 因此,请不要使用它。 All you care about is that these things are all function pointers: 您只关心这些都是函数指针:

typename <typename... F>
static std::vector<VoidFunc> registerFunctions(F*... funcs)
{
    static_assert((std::is_function_v<F> && ...));
    return { reinterpret_cast<VoidFunc>(funcs)... };
}

If you do need the signatures for something else, you can just pass each element of funcs into a different function template and just re-deduce the actually signature there. 如果确实需要其他特征的签名,则可以将funcs每个元素传递到不同的函数模板中,然后重新推导那里的实际签名。


Note that the typename is unnecessary there, and the constexpr in C++17 makes this ill-formed (since you cannot in C++17 have a constexpr std::vector ). 请注意, typename是不必要的存在,我们的constexpr在C ++ 17,使本病的形成(因为你不能在C ++ 17有constexpr std::vector )。

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

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