c++ - 成为模板模板参数的 friend

标签 c++ templates friend template-templates

我有一个带有模板模板参数的类模板,我想将这个参数(即它的所有特化)声明为 friend。但我找不到正确的语法。

template <template <class> class T>
struct Foo {

    template <class U>
    friend T;           // "C++ requires a type specifier for all declarations"

    template <class U>
    friend struct T;    // "declaration of 'T' shadows template parameter"

    template <class U>
    friend struct T<U>; // "cannot specialize a template template parameter"

    pretty<please>
    lets(be) friends T; // Compiler shook its standard output in pity
};

如何将模板模板参数声明为friend

Coliru snippet

最佳答案

我发现这个问题非常值得研究。根据标准(C++ 11 及更高版本),我猜这应该可以正常工作:

template <template <class> class U>
struct identity {
    template <typename T>
    using type = U<T>;
};

template <template <class> class U>
struct Foo {
    template <typename>
    friend class identity<U>::type;
};

由于一个间接层,这里没有任何阴影和名称重用,这种情况描述如下:

cppreference:

Both function template and class template declarations may appear with the friend specifier in any non-local class or class template (...). In this case, every specialization of the template becomes a friend, whether it is implicitly instantiated, partially specialized, or explicitly specialized. Example: class A { template<typename> friend class B; }

然而,clang 和 MSVC 似乎不这么认为:见 colirugodbolt .此外,它们的错误消息似乎毫无意义,因此它看起来像是一个编译器错误(或者只是一个错误检测到的语法错误)。 GCC 可以完美地编译和执行上述代码片段,但我仍然不确定它是否是正确的解决方案。

关于c++ - 成为模板模板参数的 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42846522/

相关文章:

c++ - 跨多个文件的好友功能

c++ - 我如何在多个 GPU 上同时执行 cufftXt 和 CUDA 内核?

c++ - constexpr 的奇怪行为

c++ - 指向模板类的指针

c++ - 聚合初始化绕过私有(private)类构造函数

c++ - 如何为类声明友元函数?

c++ - 应用程序定义的异常

c++ - pybind11 保持对象存活

c++ - 为什么我们需要引用折叠规则

函数中的c++模板