友元函数模板(在非模板类中),C++。

4
如果我有一个非模板(即“普通”)类,并且希望拥有一个模板友元函数,我应该如何编写以避免导致编译器错误?以下示例可说明我的意图:
template <class T>
void bar(T* ptr);

class MyClass  // note that this isn't a template class
{
private:
    void foo();

    template <class T>
    friend void bar(T*);  // ERROR: compiler gives me all kinds of grief
};

template <class T>
void bar(T* ptr)
{
    if (ptr)
    {
        MyClass obj;

        obj.foo();
    }
}

我正在使用Visual Studio 2005,收到的具体错误是C2063错误,指出“bar”不是一个函数。这里需要做什么不同的事情呢?


你确定吗?我复制了你的示例代码,在VS2005中编译没有错误。 - Fabio Ceconello
它也可以使用G++ 3.4.5编译而没有错误。 你在这里展示的代码很好。也许错误是由其他原因引起的? - e.James
你的代码肯定没问题。错误可能出在其他地方。 - Johannes Schaub - litb
我会相信你的话并在其他地方继续寻找。感谢你的帮助! - Brian
可能重复问题:如何将结构体模板标记为友元? - Lightness Races in Orbit
2个回答

4

您确定发布的内容出现了错误吗?我使用 Visual Studio 2005 进行以下操作,一切正常:

#include <iostream>
template <class T>
void bar(T* ptr);

class MyClass  // note that this isn't a template class
{
private:
    void foo();

    template <class T>
    friend void bar(T*);  // ERROR: compiler gives me all kinds of grief
};

void MyClass::foo()
{
    std::cout << "fooed!" << std::endl;
}

template <class T>
void bar(T* ptr)
{
    if (ptr)
    {
        MyClass obj;

        obj.foo();
    }
}


int _tmain(int argc, _TCHAR* argv[])
{

    int someObj = 1;
    bar(&someObj);

    return 0;
}

0

这更像是一种变通方法而不是修复方法,但您是否尝试将专业化列表列为好友?


是的,但由于有许多潜在的专业化领域,我想避免这种情况。 - Brian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接