Skip to content

CPP Surprise

阿毛 edited this page Jan 17, 2019 · 2 revisions

C++ Surprise

emmmm

C++ 活到老学到老,总能发现新惊喜。

Argument-dependent lookup

在做云信定义了如下方法

namespace nimlib
{
	IYixinCore_Create();
	ISerivce * GetServiceFromCore(int service_id);
}

在实际使用过程中会发现

int main()
{
	IService *service = GetServiceFromCore(); // compile success
	IYixinCore_Create();	//compile error
	return 0;
}

理由是在这过程中使用了基于实参的名字查找机制,即所谓的 Argument-dependent lookup。即为了某些场景的便利所提供的忽略 namespace 的名字查找方式,常见场景是运算符重载这种特殊函数。

具体可以参考 12

Bad BOOL Macro

iOS 32位下 BOOL 实际上并不是 bool,而是 signed char,则导致使用 runtime 做 model => json 时容易出错,当定义 BOOL 为真时,json value 为 1 而不是 true。

#if defined(__OBJC_BOOL_IS_BOOL)
    // Honor __OBJC_BOOL_IS_BOOL when available.
#   if __OBJC_BOOL_IS_BOOL
#       define OBJC_BOOL_IS_BOOL 1
#   else
#       define OBJC_BOOL_IS_BOOL 0
#   endif
#else
    // __OBJC_BOOL_IS_BOOL not set.
#   if TARGET_OS_OSX || 0 || (TARGET_OS_IOS && !__LP64__ && !__ARM_ARCH_7K)
#      define OBJC_BOOL_IS_BOOL 0
#   else
#      define OBJC_BOOL_IS_BOOL 1
#   endif
#endif

#if OBJC_BOOL_IS_BOOL
    typedef bool BOOL;
#else
#   define OBJC_BOOL_IS_CHAR 1
    typedef signed char BOOL; 
    // BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
    // even if -funsigned-char is used.
#endif