C++ 使成员对象未命名 [英] C++ make member object unnamed

查看:61
本文介绍了C++ 使成员对象未命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写方便的颜色管理类,这将允许我使用不同的组件顺序和基本不同的设置.我希望它在编译时是可区分的.假设我有这个代码:

I want to write convinient Color management class, that would allow me to use different orders of components and basically different setups. I want it to be distinguishable at compile-time. Lets say I have this code:

template <typename _valueType>
struct RGBAColorData {
    using ValueType = _valueType;
    union {
        struct { ValueType r, g, b, a; };
        ValueType components[4];
    };
};

这(即使匿名结构是非标准的)工作正常,当我想像这样使用它时:

This (even if anonymous structs are non-standard) works fine, when I want to use it like this:

RGBAColorData color;
color.r = whatever;

然而,这不是我代码的最终形式.我希望它具有拥有"类模板,这将在编译时在 XYZColorData 之间进行选择.假设它看起来像这样:

However, this is not the final form of my code. I want it to have "owning" class template, that would in compile-time select between XYZColorData. Lets say it looks like this:

template <typename _valueType, template <typename> _dataScheme>
struct Color
{
    using ValueType = _valueType;
    using DataScheme = _dataScheme<ValueType>;

    // what now?
    // DataScheme data; // ???
};

这是一个问题,因为我希望我的代码像这样使用:

This makes a problem, because I want my code to be used like this:

using RGBAColorF = Color<float, RGBAColorData>;
RGBAColorF brushColor;
brushColor.r = whatever;

这将是使用颜色的一种非常方便的方式,但是我想不出任何解决此问题的方法.最后,也许我对此有错误的方法,也许这可以用更少的努力来完成,但是我想不出任何其他不涉及大量模板类专业化的方法.

This would make a really convinient way to use colors, however I can't think of any solution to this problem. Finally, maybe I have wrong approach to this and maybe this can be done with less effort, however I can't think about any other method that wouldn't involve massive amount of template class specializations.

推荐答案

最后,我决定使用继承(正如 Ben Voigt 所说).我使用这个答案提出的绝妙方法解决了另一个问题,联合使代码不安全:
https://stackoverflow.com/a/494760/4386320

Finally, I decided to use inheritance (as Ben Voigt said). I fixed the other problem, with unions that made code unsafe, using the brilliant method proposed by this answer:
https://stackoverflow.com/a/494760/4386320

这篇关于C++ 使成员对象未命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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