我正在尝试将全局函数声明为类的“友元”:
namespace first
{
namespace second
{
namespace first
{
class Second
{
template <typename T> friend T ::first::FirstMethod();
};
}
}
}
当我在 Visual C++ 2008 下编译此代码时,我得到:
error C3254: 'first::second::first::Second' : class contains explicit override 'FirstMethod' but does not derive from an interface that contains the function declaration
error C2838: 'FirstMethod' : illegal qualified name in member declaration
如果我使用template <typename T> friend T first::FirstMethod();
相反,我得到:
error C2039: 'FirstMethod' : is not a member of 'first::second::first'
声明友元函数的正确方法是什么?
最佳答案
您已点击my quiz意外 - 序列 T::first::...
被解释为单个名称。您需要在冒号和 T
之间放置一些标记。链接的问题中也提供了解决方案。
请注意,无论如何,您首先还必须在其各自的命名空间中声明由限定名称指定的函数。
编辑:语法问题有不同的解决方案
template <typename T> friend T (::first::FirstMethod)();
template <typename T> T friend ::first::FirstMethod();
如果你经常需要引用外部命名空间并且对这种语法有疑问,你可以引入命名空间别名
namespace first
{
namespace outer_first = ::first;
class Second
{
template <typename T> friend T outer_first::FirstMethod();
};
}
关于c++ - 在 Visual Studio 2008 下声明 "friend"函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3167565/