c++ - 在 Visual Studio 2008 下声明 "friend"函数失败

标签 c++ visual-studio-2008 friend-function

我正在尝试将全局函数声明为类的“友元”:

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/

相关文章:

C++中Java8 lambda类型的比较

c++ - C++中移动构造函数的调用

c++ - 在 Visual Studio 2008 中使用 Boost 时出错

c++ - 为什么要用友元函数来定义比较运算符?

c++ - 如何在将内部类作为参数的命名空间中声明友元函数?

C++ 17 友元函数声明和内联命名空间

c++ - 轻量级 C++ 脚本库

c++ - 静态QT编译问题

c++ - 为什么 'unspecified_bool' 对于对其包装类型具有内部转换的类失败?

c# - 调试 C# WinForm 应用程序