使用C ++中的模板声明可选的类字段 [英] Declaring an optional class field using templates in C++

查看:45
本文介绍了使用C ++中的模板声明可选的类字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在需要静态声明所有内容的嵌入式环境中使用模板.我想知道是否可以使用模板或类似技术在类中声明可选字段.

I am using templates in an embedded environment where I need to statically declare everything. I would like to know if there is any way of declaring an optional field in a class using templates or similar technique.

现在在一个类中,我正在尝试做类似的事情...

Now in one of the classes I am trying to do something like this ...

template<typename Filter, typename Compensation.....> 
class MeasurementChannel {

private:
  if constexpr( !std::is_same<Compensation, void>){
    Compensation _comp; // this is an optional field
  }

  ....

  ....

};

现在这行不通了,在实际示例中,我可能有4+种不同的可插拔组件,例如Compensation,这使部分专业化成为一个问题,因为因为我需要16个专业化来处理每个对象中void的不同组合,可选职位.

Now this doesn't work and in the real example I have maybe 4+ different pluggable components like Compensation that makes partial specialisation a problem because because I would need 16 specialisations just to deal with the different combinations of void in each of the optional positions.

到目前为止,我提出的最好方法是创建一个空类(在本例中为NullComp),该空类实现基本接口,但不执行任何操作,并且当用户不希望该组件功能作为其一部分时被用户替换模板化的类.根据编译器的优化级别,将要生成的大多数代码都被优化掉了,但是我希望能够保证一开始就不会创建任何东西..

The best way I have come up so far is to create a null class (NullComp in this case) that implements the basic interface but does nothing and gets substituted by the user when they don't want that component functionality as part of the templated class. Depending on the compiler optimisation level, most of the code that would be generated is optimised away, but I would like to be able to guarantee that nothing is created in the first place. .

所以我的问题基本上可以归结为模板中是否有任何方法可以选择将字段声明为类的一部分.也就是说,有一些技术可以将std :: enable_if与方法结合使用.

So my question basically boils down to is there any way in templates of optionally declaring a field as part of a class. I.e is there some technique that gives the equivalent of using std::enable_if with methods.

或者我只是试图做错这个,并且有一种简单而优雅的方式来构成模板,该模板使用某种完全不同的技术来达到相同的最终目标.

Alternatively am I just trying to do this wrong and there is a simple elegant way of composing templates that reaches the same end goal using some completely different technique.

推荐答案

  1. 您可以对它进行部分专业化处理:

template<class Filter> class MeasurementChannel<Filter, void> {};

  1. 或者,要不将所有的类代码都复制为部分专业化,则只能对相关部分进行专业化:

template<class Compensation> class CompHolder {
protected:
    Compensation comp; // don't start identifiers with underscores
};

template<> class CompHolder<void> {};

template<class Filter, class Compensation> class MeasurementChannel
    : CompHolder<Compensation>
{
};

这篇关于使用C ++中的模板声明可选的类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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