1

I'm trying to pass an enum which is basically a byte to a overload resolution, but it doesn't work.

Here is the enum:

enum class WriteOp : uint8_t {
  kAdd = 0,
  kDelete
};

Here are the overloads:

 void copy_out(uint8_t& v) { getn((char*) &v, 1); }
 void copy_out(uint16_t& v) { getn((char*) &v, 2); }
 void copy_out(uint32_t& v) { getn((char*) &v, 4); }
 void copy_out(uint64_t& v) { getn((char*) &v, 8); }

And here is a typical error messages I'm getting:

main.cpp:164:8: note: candidate function not viable: no known conversion from 'WriteOp' to 'uint8_t &' (aka 'unsigned char &') for 1st argument
void copy_out(uint8_t& v) { getn((char*) &v, 1); }

Any simple and elegant way to do that?

Frank
  • 4,341
  • 8
  • 41
  • 57

2 Answers2

2

You have a strongly typed enum the whole point of these are they are not implicitly convertible and can have scope. You can do 1 of 3 things:

  1. Create an overload for your type: void copy_out(WriteOp& v) { getn((char*) &v, 1); }
  2. Explicitly cast your enum copy_out(&(uint8_t)my_enum);
  3. Use a standard enum.

enum WriteOp {
  kAdd = 0,
  kDelete
};
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • Note that many compilers support sized non-class enums. Oh, and are you certain that an eum can be implicitly cast to a reference to its underlying type? Or that its underlying type is one of those types? – Yakk - Adam Nevraumont Aug 19 '15 at 21:20
2
template<class E,
  std::enable_if_t<std::is_enum<E>{}>* = nullptr
>
void copy_out(E& e){
  getn(reinterpret_cast<char*>(&e),sizeof(e));
}

if you are taking an enum, take an enum.

The above takes any enum, and does a getn.

With a bit of refactoring, you could move all calls to getn and its unsafe casts into one function.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524