Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class as enum-like, or with a specific value

Tags:

c++

I would like my function to accept a compression-level (which can take values 0..9). I want the user to be able to set the level manually Compression(7) or use some defaults like Compression::High, Compression::Medium.

I thought of the following:

class Compression {
public:
    Compression(size_t level) : m_level(level) {};
    static const Compression Medium;
    static const Compression High;
    size_t get() const { return m_level; };
private:
    size_t m_level;
};

const Compression Compression::High{9};
const Compression Compression::Medium{5};

The problem is that I am developing a header-only library, and doing this leads to "multiple definitions of 'Compression::High' and 'Compression::Medium". How can this be solved?


Edit

Challenges:

  • I only want to have one function overload foo(Compression) that acts on the Compression option (foo(size_t) is already in use for something else).
  • I'm stuck to C++11 (maybe C++14, but not higher).
like image 337
Tom de Geus Avatar asked Jan 17 '26 08:01

Tom de Geus


1 Answers

GCC version 9.3.0 accepts that code (C++17):

inline const Compression Compression::High{9};
inline const Compression Compression::Medium{5};

Please note the inline word.

like image 194
0x0000 Avatar answered Jan 20 '26 01:01

0x0000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!