繁体   English   中英

模板化 class 中的成员变量

[英]Template a member variable in a class

我正在对一些较旧/杂乱的代码进行一些重构。 我正在尝试一点一点地改进。 因为它适合这个项目,我开始在一些 class 上实现 CRTP(对于 static 多态性),我们称之为sensor 通过 CRTP,现在有一个real和一个fake的实现。

现在,我正在尝试将模板放入使用sensor的 class ( interface_actions )中。 我得出了这样的结论:

class interface_actions
{
public:
    template <class implementation>
    interface_actions(sensor<implementation> detector)
    : _detector(detector)
    {}

    // Lots of stuff that I don't want to touch

private:
#if (SOMETHING)
    sensor<real> _detector;
#else
    sensor<fake> _detector;
#endif
};

如您所见,我不知道如何处理_detector而无需将整个 class 制作为模板,因此我使用了预处理器...

我想这更像是一个架构问题,但是您如何让 go 让_detector采用传感器而不使整个 class 成为模板? 在我看来,我必须从根本上重写这部分代码,但也许有更简单的方法?

您可以使用std::conditional_t

class interface_actions
{
    std::conditional_t<SOMETHING, sensor<real>, sensor<fake>> _detector;
};

如果SOMETHING产生true_detector将是sensor<real>类型,否则sensor<fake>

但这仅在SOMETHING位于class interface_actions的 scope 之外时才有效,否则您必须使 class 采用模板。 正如 pptaszni 建议的那样,您可以创建一个默认模板参数来“隐藏”模板参数,因此您的旧代码中显示interface_actions object; 不会受到影响:

template<bool is_real = true>
class interface_actions
{
    std::conditional_t<is_real, sensor<real>, sensor<fake>> _detector;
};


int main() {
    interface_actions foo;
    static_assert(std::is_same_v<decltype(foo._detector), sensor<real>>);
}

暂无
暂无

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

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