Skip to content

Commit

Permalink
Add a type cast to RCT_ENUM_CONVERTER for C++ compatibility
Browse files Browse the repository at this point in the history
Summary:
C++ doesn't provide an implicit cast to an enum value from the enum's backing type. When a `.mm` file calls `RCT_ENUM_CONVERTER`, we end up with the following compiler error:
> Error: cannot initialize return object of type `<TypeName>` with an rvalue of type `NSInteger`

Since `RCT_ENUM_CONVERTER` is a macro, this error will appear whenever we try to expand the macro in a C++ context.

The project compiles and runs as expected when this additional cast is added 😃
Closes #14408

Reviewed By: javache

Differential Revision: D5215584

Pulled By: jballer

fbshipit-source-id: 7f4464afd7cd9dc9a014f646278bae20731f08ba
  • Loading branch information
jballer authored and facebook-github-bot committed Jun 16, 2017
1 parent a555551 commit eaac3b5
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions React/Base/RCTConvert.h
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,17 @@ RCT_CUSTOM_CONVERTER(type, name, [json getter])
#define RCT_NUMBER_CONVERTER(type, getter) \
RCT_CUSTOM_CONVERTER(type, type, [RCT_DEBUG ? [self NSNumber:json] : json getter])

/**
* When using RCT_ENUM_CONVERTER in ObjC, the compiler is OK with us returning
* the underlying NSInteger/NSUInteger. In ObjC++, this is a type mismatch and
* we need to explicitly cast the return value to expected enum return type.
*/
#ifdef __cplusplus
#define _RCT_CAST(type, expr) static_cast<type>(expr)
#else
#define _RCT_CAST(type, expr) expr
#endif

/**
* This macro is used for creating converters for enum types.
*/
Expand All @@ -218,7 +229,7 @@ RCT_CUSTOM_CONVERTER(type, type, [RCT_DEBUG ? [self NSNumber:json] : json getter
dispatch_once(&onceToken, ^{ \
mapping = values; \
}); \
return [RCTConvertEnumValue(#type, mapping, @(default), json) getter]; \
return _RCT_CAST(type, [RCTConvertEnumValue(#type, mapping, @(default), json) getter]); \
}

/**
Expand All @@ -233,7 +244,7 @@ RCT_CUSTOM_CONVERTER(type, type, [RCT_DEBUG ? [self NSNumber:json] : json getter
dispatch_once(&onceToken, ^{ \
mapping = values; \
}); \
return [RCTConvertMultiEnumValue(#type, mapping, @(default), json) getter]; \
return _RCT_CAST(type, [RCTConvertMultiEnumValue(#type, mapping, @(default), json) getter]); \
}

/**
Expand Down

0 comments on commit eaac3b5

Please # to comment.