具有不同类型的非类型参数的C ++可变参数模板 [英] C++ variadic template with non-type parameters of different types

查看:155
本文介绍了具有不同类型的非类型参数的C ++可变参数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个类,该类接受一系列非类型参数,可能是不同类型的参数。例如,以下内容应有效:

I would like to define a class which takes a list of non-type parameters, potentially of different types. For example, the following should be valid:

Test<3, 4.5, 6> t;

如果所有参数的类型相同,请说 int ,我可以使用以下定义:

If all parameters had the same type, say int, I could use the following definition:

template<int... args>
class Test {
  // ...
};

更具体地说,在我的特定用例中,有第二类 Base 有很多成员,我想传递 Base 成员指针。

To be more specific, in my specific use case there is a second class Base with a number of members, and I would like to pass Base member pointers.

Test<&Base::a, &Base::b>

如果 Base :: a Base :: b 具有通用类型 T ,那么我可以定义 Test

If Base::a and Base::b have a common type T, then I could define Test as follows.

template<int Base::* ...args>
class Test {
  //
};

如何定义这样的类 Test

推荐答案

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

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 关键字。

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

这篇关于具有不同类型的非类型参数的C ++可变参数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆