问题描述
使用Objective-C ++,如果且仅当T为Objective-C类时,我才能编写C ++ IsObjectiveCClass<T>
模板元函数,使IsObjectiveCClass<T>::value
为true吗?
Using Objective-C++, can I write a C++ IsObjectiveCClass<T>
template metafunction such that IsObjectiveCClass<T>::value
is true if and only if T is an Objective-C class?
从语言的C/C ++子集的角度来看,ObjC类到底是什么?当在C/C ++上下文中使用时,MyClass *指针的行为似乎与普通的C指针相同.这是否意味着MyClass也是C类型?
Exactly what are ObjC classes from the viewpoint of the C / C++ subset of the language? When used in a C / C++ context, MyClass* pointers seem to behave like ordinary C pointers; does that mean that MyClass is also a C type?
推荐答案
以下是一种简化的解决方案,该解决方案在大多数情况下(如果不是全部,有人可以想到这可能会失败吗?)(在xcode中使用clang 3.0) 4.2-对于早期的clang版本,请使用typedefs而不是使用别名):
Here is a simplistic solution that should work in most (if not all? Can anyone think of when this might fail?) cases (it uses clang 3.0 via xcode 4.2 - use typedefs instead of using aliases for earlier clang versions):
template<class T> struct IsObjectiveCClass
{
using yesT = char (&)[10];
using noT = char (&)[1];
static yesT choose(id);
static noT choose(...);
static T make();
enum { value = sizeof(choose(make())) == sizeof(yesT) };
};
这篇关于Obj-C ++:用于识别Objective-C类的模板元功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!