考慮下面的代碼:MSVC友元函數聲明錯誤
#include <cstddef>
template<size_t value> class dummy { };
class my_class
{
int m_member;
// Overload 1
template<size_t value>
friend void friend_func(dummy<value>*);
// Overload 2
template<size_t value>
friend void friend_func(int(*)[value]);
};
// Overload 1
template<size_t value>
void friend_func(dummy<value>*)
{
my_class instance;
instance.m_member = value;
}
// Overload 2
template<size_t value>
void friend_func(int(*)[value])
{
my_class instance;
instance.m_member = value;
}
int main(int argc, char* argv[])
{
dummy<5> d;
friend_func(&d); // call Overload 1
int arr[5];
friend_func(&arr); // call Overload 2 - error in MSVC!
return 0;
}
正如你可以看到,這兩個功能之間的唯一區別是第二個採用指向value
int
!而非dummy<value>
。 此代碼編譯在GCC就好($ GCC-4.7.2 TEST.CPP)和鏘(感謝WhozCraig),但拋出MSVC以下錯誤(我測試2012):
1>d:\path\to.cpp(32): error C2248: 'my_class::m_member' : cannot access private member declared in class 'my_class'
1> d:\path\to.cpp(8) : see declaration of 'my_class::m_member'
1> d:\path\to.cpp(7) : see declaration of 'my_class'
1> d:\path\to.cpp(40) : see reference to function template instantiation 'void friend_func<5>(int (*)[5])' being compiled
對我來說,這看起來就像一個錯誤。但是,有沒有人曾經遇到過這樣的行爲?這真的是一個錯誤,或者是錯誤的原因?任何快速解決方法?
編輯:我已經能夠找到一個妥善的解決方法,請參閱answer below。
它可能不會幫助鏗鏘吃這個沒問題。 – WhozCraig 2013-03-01 02:54:20