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,我得到的具体错误是error C2063,指出“bar”不是函数。这里需要做些什么不同的事情?

4

2 回答 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;
}
于 2009-01-19T19:46:36.120 回答
0

这更像是一种解决方法而不是修复,但是您是否尝试将专业列为朋友?

于 2009-01-19T19:37:27.107 回答