简体   繁体   中英

C++ bracket operator for castable types

Setup.

enum class A { ... };
std::vector<B> bs;
A a = A::foo;
bs[a].bar(); // not going to compile, A isn't an integer

I want to be able to write this as it is very convenient. The easiest way I see is to write a free function bracket overload operator.

template<class T> inline constexpr
underlying_type_t<T> underlying_cast(T t)
{ return static_cast<underlying_type_t<T>>(t); }

B& operator[](std::vector<B>& b, A a)
{ return b[underlying_cast(a)]; }

Is something like this possible?

You cannot overload operator[] outside the class definition. If you want an overload that takes an argument of the enum A , you have to define a subclass of std::vector and add the overload within the subclass.

Example:

#include <vector>

template<class Enum, class Val>
class VectorByEnum : public std::vector<Val>
{
public:
    using std::vector<Val>::vector; // inherit constructors

    Val & operator[](Enum idx)
    {
        typedef typename VectorByEnum::size_type idx_t;
        return std::vector<Val>::operator[](static_cast<idx_t>(idx));
    }
};

enum class A {
    One,
    Two
};

class B
{
public:
    int bar() { return 0; }
};

int main(void)
{
    VectorByEnum<A, B> v(2);
    return v[A::Two].bar();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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