问题
template instantiation check for member existing in class explains how to check if a class member exists in a template. However, given a set of processes within a switch (NOT a template) is there a way to handle a member check case. It should be similar to something like this. Note that the actual class definition is not under my control and is being created in a future release of header files and libraries that I am using.
I am aware that this preprocessor example would not work, but since this is not a template, how would this processing be set up?
case myCase:
{
#ifdef myClass.memberA
myClass.memberA varName;
// other processing using varName
#else
//Alternate processing
#endif
break;
}
回答1:
You can have two template overloads of the work you want:
template<class T>
void process_myCase(T& obj, std::true_type);
template<class T>
void process_myCase(T& obj, std::false_type);
Then in your case
call the function with the second parameter computed by the method you mention in the beginning of the question.
The first overload will be instantiated for classes with the required member while the second overload will be instantiated for all the rest.
I don't think a non-templated way will work but then again since these templates can be placed in your cpp file I don't see what drawback there is for them being templates.
来源:https://stackoverflow.com/questions/28657982/c-class-member-check-if-not-a-template