overload scoped enum assignment operator

Yeah, I don't suppose there is a way?

(It's totally legitimate! Honest!)

[But it's probably a design flaw.]

I'm playing with some colors.
There are foreground colors.
And there are background colors.

The actual colors are the same. It's just really nice to be able to have the compiler switch based upon the foreground-ness or background-ness of the color for you.

Oh, and there's a 'both' class.

And now I'd like to be able to say
1
2
3
4
bgtextcolor bg;
fgtextcolor fg = fgtextcolor::light_red;
...
bg = fg;

But wait! Assignment operators are apparently too special to be declared outside of a class.

(I used to wonder why, but I didn't ever see what difference it would make. Until now. So... any way around it?)


Thanks for reading. Again. :o]
An elaborate mechanism would be to wrap one of the scoped enums in a class.
I tend to favour a simpler approach: provide explicit conversion operations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
namespace elaborate
{
    enum class bkcolour { CYAN, MAGENTA, YELLOW } ;

    struct fgcolour // wrap the scoped enum
    {
        enum class fgcolour_ { CYAN, MAGENTA, YELLOW } ;
        fgcolour_ clr ;

        fgcolour( fgcolour_ clr = MAGENTA ) : clr(clr) {}
        fgcolour( bkcolour bkclr ) : clr( fgcolour_( int(bkclr) ) ) {}
        fgcolour& operator= ( bkcolour bkclr ) { clr = fgcolour_( int(bkclr) ) ; return *this ; }

        operator fgcolour_() const { return clr ; }
        operator bkcolour() const { return bkcolour( int(clr) ) ; }

        static constexpr fgcolour_ CYAN = fgcolour_::CYAN ;
        static constexpr fgcolour_ MAGENTA = fgcolour_::MAGENTA ;
        static constexpr fgcolour_ YELLOW = fgcolour_::YELLOW ;
    };

    // static_assert( bkcolour::CYAN == fgcolour::CYAN && etc.
}

namespace simple //
{
    enum class bkcolour { CYAN, MAGENTA, YELLOW } ;
    enum class fgcolour { CYAN, MAGENTA, YELLOW } ;

    // static_assert( bkcolour::CYAN == fgcolour::CYAN && etc.

    fgcolour colour_cast( bkcolour bkclr ) { return fgcolour( int(bkclr) ) ; }
    bkcolour colour_cast( fgcolour fgclr ) { return bkcolour( int(fgclr) ) ; }
}

int main()
{
    {
        using namespace elaborate ;
        fgcolour fg = fgcolour::YELLOW ;
        bkcolour bg = bkcolour::MAGENTA ;
        fgcolour fg2 = bg ;
        bkcolour bg2(fg) ;
        fg = bg2 ;
        bg = fg2 ;
    }

    {
        using namespace simple ;
        fgcolour fg = fgcolour::CYAN ;
        bkcolour bg = bkcolour::MAGENTA ;
        fg = colour_cast(bg) ;
        bg = colour_cast(fg) ;
    }
}
Thank you, that answers my question.
I'll continue to use the explicit conversion functions...
Topic archived. No new replies allowed.