考虑下面的代码: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