开发者

Can I use enum class values as arguments to varargs functions?

C++11 adds enum cla开发者_JAVA技巧sses, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜