c++ - 在某个命名空间中定义方法时在全局命名空间中声明?

标签 c++ visual-studio templates namespaces

我的代码包含两部分 - 命名空间 my 中的类模板 test 和全局命名空间中的函数 frobnicate。类模板想在它的一个方法中使用这个函数,我想在它的使用附近声明它:

namespace my
{
    template <class T>
    struct test
    {
        void do_stuff(T& i)
        {
            void frobnicate(T&);
            frobnicate(i);

            // more code here
        }
    };
}

struct SomeClass {};

void frobnicate(SomeClass& i)
{
    // some code here
}

int main()
{
    my::test<SomeClass> t;
    SomeClass object;
    t.do_stuff(object);
}

由于错误(描述为 here ),这在 MS Visual Studio 2017 中有效,因为 Visual Studio 在全局命名空间中声明函数,而根据标准,此类声明在当前命名空间中声明函数。

但是,gcc 理所当然地提示:

... undefined reference to `my::frobnicate(SomeClass&)'

我可以让它在 gcc 或任何其他符合标准的编译器中工作吗?


如果我在声明模板test 之前放置frobnicate 声明,代码就可以工作。然而,在我的实际代码中,这两部分代码位于不相关的头文件中,如果可能的话,我希望我的代码无论 #include 的顺序如何都能正常工作。

最佳答案

只需在命名空间之前将您的 frobnicate 函数声明为模板即可。

template <class T>
void frobnicate(T&);

namespace my {

template <class T>
struct test
{
    void do_stuff(T& i)
    {
        frobnicate(i);
        // more code here
    }
};
}  // close my namespace

关于c++ - 在某个命名空间中定义方法时在全局命名空间中声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54735501/

相关文章:

c++ - 让 boost::function 引用我的函数对象

c++ - 程序的密码

windows - DirectX SDK项目-移植到VS2012

c# - 使用 ImageBrush 启动时程序崩溃

c++ - 具有透明度的 MFC 图像按钮

c++ - 由于C++17支持数组的shared_ptr,这是否意味着ctor和reset中不再需要T[]的显式删除器?

C++ 将控制台窗口置于最前面

c++ - 在 C++ 中返回更大值的模板函数

C++ 模板结构 'has no member named' 错误

c++ - 来自不同命名空间的模板模板参数可以成为 friend 吗?