【问题标题】:Friend template functions (in non-template classes), C++友元模板函数(在非模板类中),C++
【发布时间】:2009-01-19 19:19:38
【问题描述】:

如果我有一个非模板(即“普通”)类并希望有一个模板友元函数,我如何编写它而不导致编译器错误?这是一个示例来说明我正在尝试做的事情:

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”不是函数。这里需要做些什么不同的事情?

【问题讨论】:

  • 你确定吗?我复制了你的示例代码,它在 VS2005 中编译没有错误。
  • 它也可以使用 G++ 3.4.5 无错误地编译。您在此处显示的代码很好。也许错误是由其他原因引起的?
  • 您的代码绝对正确。错误在其他地方
  • 我会相信你的话并继续寻找其他地方。感谢您的所有帮助!

标签: c++ function templates friend


【解决方案1】:

您确定您发布的内容会导致错误吗?以下(使用 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;
}

【讨论】:

    【解决方案2】:

    这与其说是一种修复,不如说是一种变通方法,但您是否尝试过将专业化列为好友?

    【讨论】:

    • 是的,但由于有许多潜在的专业,我想避免这种情况。
    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 2014-10-03
    • 2016-06-23
    • 2016-10-19
    • 2013-09-18
    相关资源
    最近更新 更多