c++ - 声明模板友元类的两种方法?

标签 c++ templates

template<typename T> class FooBar {};

template<typename T> class Bar {
    friend class FooBar<T>;
};

template<typename T> class Bar2 {
    template friend class FooBar<T>;
};

类 Bar 和 Bar2 有什么区别?

最佳答案

根据我的编译器,你的第二个语法无效。如果您将它们更改为:

template<typename T> class FooBar {};

template<typename T> class Bar {
    friend class FooBar<T>;
};

template<typename T> class Bar2 {
    template<typename T2> friend class FooBar;
};

然后它会编译。不同之处在于 Bar<T> , 只有 FooBar<T>是 friend ;如果你有 Bar<int> , 只有 FooBar<int>是 friend ,不是FooBar<char>或任何其他类型,但 int .在 Bar2<T> , 任何类型的 FooBar是 friend 。

关于c++ - 声明模板友元类的两种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970529/

相关文章:

c++ - 如何在 C++ 中每个值只调用一次函数?

php - 简单手工制作的 PHP 模板引擎无法工作!请帮助

c++ - 使用额外的不可推导模板参数重载函数是否有效?

c++ - 类模板特化中的成员变量别名

c++ - 为什么模板不隐式实例化为 const 或引用类型?

c++ - 使用ofstream,c++将引号写入文本文件

c++ - 如何专门化 std::vector<T> 的模板成员函数

c++ - 检查元素是否存在于动态分配的数组C++中

c++ - CRT 未检测到 DLL 中的内存泄漏

C++:组合私有(private)全局变量和模板