I want that when passing a certain enumeration property, the corresponding operator with type checking is output, here is a simple code example
#include <iostream>
#include <typeinfo>
//#include <memory>
enum MessageType : uint16_t
{
Display,
Warning,
Error
};
#define MESSAGE(_MessageType, _Text)\
if((_MessageType == Display) && (typeid(_MessageType).name() == MessageType))\
{\
std::cout<<"Display: "<<_Text;\
}\
else if((_MessageType == Warning) && (typeid(_MessageType).name() == MessageType))\
{\
std::cout<<"Warning: "<<_Text;\
}\
else if ((_MessageType == Warning) && (typeid(_MessageType).name() == MessageType))\
{\
std::cout<<"Error: "<<_Text;\
}\
else\
return
int main()
{
MESSAGE(Display, "Text!"); // type name is not allowed
return 0;
}
CodePudding user response:
std::type_info::name
returns a c-string. MessageType
is not a string, its the name of a type. You can compare the string returned from typeid(_MessageType).name()
to the string returned from typeid(MessageType).name()
.
However, identifiers starting with leading _
followed by capital letter are reseved. If you use them your code has undefined behavior. Moreover main
is not void
you must return an int
.
And last but not least, you don't need typeid
when you can use constexpr if
and std::is_same
. A simple function instead of macro would also make it much easier to get a compiler error when the type does not match. Currently your check for the right type is made at runtime. I see no reason to use a macro here, the same could be achieved without one.