C++11 adds enum classes, which are stronger-typed enums - values of enum classes will not be implicitly converted to values of other enum classes or integers, and forward-declarations are permitted by virtue of an explicit size specifier.

Is it possible to pass values of such enumerations to varargs functions and remain within standards-defined behavior? Within implementation-defined behavior?

有帮助吗?

解决方案

Yes, you can. 5.2.2/7 explicitly allows arguments of any enumeration type. Unscoped enum values are integer promoted, but scoped enums (the enum class ones) are not.

Of course you still have to be careful in the implementation of the function.

其他提示

I think the answer is that it can be safe:

VA_ARGS requires arguments to be POD, that hasn't changed as far as I'm aware.

I can't see any reason why:

enum class foo { bar=1 };

Wouldn't meet the requirements for POD-ness though.

As you throw away some type information when using varargs (that's why it's strongly discouraged for non POD types) you will just receive the underlying type at the other end of your varargs using function. The default is int but you can change that (e.g. enum class MyEnum : char { ... };)

Corrected: varargs does indeed not throw away all type information and if you use POD data type you should be quite safe.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top