根据模板参数条件C ++ 17创建成员别名 [英] Create member alias based on a template parameter condition C++17

查看:74
本文介绍了根据模板参数条件C ++ 17创建成员别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图简化通用类的使用,并遇到以下想法:

So, I am trying to simplify the use of my generic classes and came across the following idea:

template <size_t size>
struct Vector {
    std::array<float, size> data;

    float& x = data[0];
    float& y = data[1]; // Declare y only if size is > 0
    float& z = data[2]; // Declare z only if size is > 1
    float& w = data[3]; // Declare w only if size is > 2
};

很明显,如果我尝试像这样运行程序,则数组将抛出超出范围的异常.

Obviously, if I try to run the program like this, the array will throw an out of range exception.

现在只有在给出条件(在编译时已知)的情况下,才可以声明这些别名吗?

Now is there a way to declare these aliases only if the condition (known at compile time) is given?

我以std :: enable_if:

template <size_t size>
struct Vector {
    std::array<float, size> data;

    float& x = data[0];
    declare_if<(size > 0), float&> y = data[1];
    declare_if<(size > 1), float&> z = data[2];
    declare_if<(size > 2), float&> w = data[3];
};

此外,我会最好不要让该类从另一个类派生,或者完全专门化该类.

Also, I would prefer to not let the class derive from another, or fully specialize the class.

推荐答案

AFAIK,您可以做到这一点,并且仅通过继承或专业化来保留语法.

AFAIK you can do that and keep your syntax only with inheritance or specialization.

如果要避免这种情况,您需要稍微更改一下界面.您需要制作xyzt方法.实际上是方法模板:

If you want to avoid that you need to change a bit the interface. You need to make x, y, z, t methods. Actually method templates:

template <size_t size>
struct Vector {
    std::array<int, size> data;

    template <std::size_t S = size, class = std::enable_if_t<(S > 0)>>
    auto x() -> int& { return data[0]; };

    template <std::size_t S = size, class = std::enable_if_t<(S > 1)>>
    auto y() -> int& { return data[1]; };

    template <std::size_t S = size, class = std::enable_if_t<(S > 2)>>
    auto z() -> int& { return data[2]; };

    template <std::size_t S = size, class = std::enable_if_t<(S > 3)>>
    auto t() -> int& { return data[3]; };  
};

Vector<2> v;

v.x();
v.y();
v.z(); // error: no matching member function for call to 'z'

这篇关于根据模板参数条件C ++ 17创建成员别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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