简体   繁体   English

在全局命名空间中声明一个返回模板类的友元函数

[英]declaring a friend function in the global namespace that returns a template class

i have a function declared in a namespace, that when it is defined as a friend, throws a compiler error.我在命名空间中声明了一个函数,当它被定义为友元时,会引发编译器错误。

#include <string>
#include <vector>

namespace Example
{
    std::vector<std::string> GetNames();
}

class MyClass
{
    public:
        MyClass() : 
                name("data")
        {}

    private:
        std::string name;

    friend std::vector<std::string> ::Example::GetNames();
};

this fails to compile with the error这无法编译错误

'Example' in 'class std::vectorstd::__cxx11::basic_string<char >' does not name a type friend std::vectorstd::string ::Example::GetNames(); 'class std::vectorstd::__cxx11::basic_string<char >' 中的 'Example' 没有命名类型朋友 std::vectorstd::string ::Example::GetNames(); ^~~~~~~ main.cpp:25:2: error: expected ';' ^~~~~~~ main.cpp:25:2: 错误:应为';' after class definition类定义后

yet if i remove the global namespace identifier, :: from ::Example::GetNames() , it will compile happily.然而,如果我删除全局命名空间标识符:: from ::Example::GetNames() ,它将愉快地编译。

how do i deal with this issue when i need to start at the global namespace due to nested namespaces?当由于嵌套命名空间而需要从全局命名空间开始时,我该如何处理这个问题?

The compiler doesn't evaluate your friend declaration as you intended it to.编译器不会按照您的预期评估您的朋友声明。 Instead, the compiler reads the following:相反,编译器读取以下内容:

    friend std::vector<std::string>::Example::GetNames();

It thinks that you want to declare the function GetNames that is within a namespace Example inside the vector class.它认为您要声明在vector类中的命名空间Example内的函数GetNames
That's why when you remove the :: the compiler can lookup the namespace Example itself and finds it in the global namespace.这就是为什么当您删除:: ,编译器可以查找名称空间Example本身并在全局名称空间中找到它。

What you want to do instead to tell the compiler that there is a global namespace called Example is to put parentheses around the function declaration:你想要做的是告诉编译器有一个名为Example的全局命名空间是在函数声明周围放置括号:

    friend std::vector<std::string> (::Example::GetNames)();

Now, this gets evaluated as you want to.现在,这将根据您的需要进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM