考虑以下代码:
#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
s 而不是 dummy<value>
。
此代码在 GCC ($ gcc-4.7.2 test.cpp) 和 Clang 中编译得很好(感谢 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 .
最佳答案
这绝对是一个错误:A template function parametrized on the size of an array cannot be declared as a friend of a class 。当 value
被推导为友元模板函数的数组大小时,就会发生这种情况。这是代码的缩短版本,可以正常编译。此示例与您的示例的代码完全相同,只是我指定了数组的大小。
class my_class
{
int m_member;
template<size_t value>
friend void friend_func(int(*)[5]);
};
template<size_t value>
void friend_func(int(*)[5])
{
my_class instance;
instance.m_member = value;
}
int main()
{
int arr[5];
friend_func<5>(&arr);
}
一种解决方法是将值
作为第二个函数参数传递:
template <typename T>
void friend_func(T, int value)
{
my_class instance;
instance.m_member = value;
}
关于c++ - MSVC 友元函数声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15149607/