Friend template functions (in non-template classes), C++

无人久伴 提交于 2019-12-07 08:04:10

问题


If I have a non-template (i.e. "normal") class and wish to have a template friend function, how do I write it without causing a compiler error? Here is an example to illustrate what I am trying to do:

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();
    }
}

I'm using Visual Studio 2005, and the specific error I'm given is error C2063, stating that "bar" isn't a function. What needs to be done differently here?


回答1:


Are you sure what you've posted gives the error? The following (using Visual Studio 2005) works fine for me:

#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;
}



回答2:


This is more of a workaround than a fix, but have you attempted to list the specializations as friends?



来源:https://stackoverflow.com/questions/458795/friend-template-functions-in-non-template-classes-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!