舉一個簡單的例子。如果我編譯以下main.mm
文件沒有ARC,它工作正常。如何使C++模板適用於使用ARC的Objective C類型?
#import <Foundation/Foundation.h>
template <typename T>
int testing(const T & whoCares) {
return 0;
}
int main(int argc, const char * argv[])
{
return testing(@"hello");
}
如果我編譯這與ARC,出現以下錯誤:
/Users/sam/Projects/TemplateTest/TemplateTest/main.mm:10:12: error: no matching function for call to 'testing'
return testing(@"hello");
^~~~~~~
/Users/sam/Projects/TemplateTest/TemplateTest/main.mm:4:5: note: candidate template ignored: substitution failure [with T = NSString *]
int testing(const T & whoCares) {
^
1 error generated.
爲什麼?更重要的是,它可以解決嗎?沒有任何進一步的解釋爲什麼替代失敗。如果我明確地通過類型,如下所示:
return testing<NSString *>(@"hello");
它的工作原理。說了這麼多,我不想,也不應該在我的代碼中做這件事。
有趣的是,這隻對Objective C類型失敗。以下替換做工精細,無論被啓用ARC的:
return testing("hello");
return testing(123);
你有沒有在您的Xcode版本切換編譯器,如果是這樣,這是否有所作爲的選項? – 2012-07-07 21:21:30
我確實(我正在使用Xcode 4.3.3)。不過,我的印象是,ARC只適用於Apple LLVM Compiler 3.1設置(這是我使用的)。 – SamCee 2012-07-07 22:25:17
您的示例在Clang版本3.2中正常工作。我懷疑@ SamCee的答案是否正確,並且該錯誤已被修復。 – Quuxplusone 2012-10-09 00:07:56