且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有不同类型的非类型参数的C ++可变参数模板

更新时间:2022-11-24 15:37:07

您可以通过以下方式进行操作:

You can do it in the following way:

template <class... Types>
struct Wrapper
{
    template <Types... args>
    class Test {
        // ...
    };
};

请注意,简单表示法 template< class ... Types,Types。 .. args> class Test; 是标准所不允许的(请参阅[temp.param] 14.1 / 15段。)

Note that simple notation template <class... Types, Types... args> class Test; is not permitted by standard (see paragraph [temp.param] 14.1/15).

使用示例(请注意 float double long double 常量不能为非常量类型模板参数):

Example of using (note that float, double and long double constants can not be non-type template parameters):

Wrapper<int, char, unsigned>::Test<1, '2', 3U> t;

具有指向成员的指针的更具体的情况可以类似地实现:

More specific case with pointers to members can be implemented similarly:

struct Base
{
    int a;
    float b;
    void c() {}
};

template <class... Types>
struct Wrapper
{
    template <Types Base::*... args>
    class Test {
        //
    };
};

使用示例:

Wrapper<int, float, void ()>::Test<&Base::a, &Base::b, &Base::c> t2;

可以使用可变参数宏和 decltype $ c $来缩短此表示法c>关键字。

This notation can be shortened using variadic macro and decltype keyword.