简体   繁体   English

结交模板模板参数

[英]Befriending a template template parameter

I've got a class template with a template template parameter, and I want to declare this parameter (that is, all of its specializations) as a friend . 我有一个带有模板模板参数的类模板,我想将这个参数(即它的所有特化)声明为friend But I can't find the correct syntax. 但我找不到正确的语法。

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

How can I declare a template template parameter as friend ? 如何将模板模板参数声明为friend

Coliru snippet Coliru片段

I've found this problem is very interesting to research. 我发现这个问题对研究很有意思。 According to standard (C++11 and above) this should works fine, I guess: 根据标准(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;
};

Due to one indirection level, there are no any shadowing and name reusing here, and this situation described as following: 由于一个间接级别,此处没有任何阴影和名称重用,这种情况描述如下:

cppreference : 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; } 示例: class A { template<typename> friend class B; } class A { template<typename> friend class B; }

However, it seems like clang and MSVC think otherwise: see coliru or godbolt . 然而,似乎clang和MSVC不这么认为:看colirugodbolt Moreover, their error messages seem meaningless, so it looks like a compiler bug (or just an incorrectly detected syntax error). 此外,它们的错误消息似乎毫无意义,因此它看起来像编译器错误(或只是错误检测到的语法错误)。 GCC compiles and executes mentioned snippets perfectly, but I still not sure it's a correct solution. GCC完美地编译和执行提到的片段,但我仍然不确定它是否是正确的解决方案。

Templates tend to get programmers to over-complicate things. 模板往往会让程序员过度复杂化。 I'm not exactly sure what you are trying to do, and I suspect that there is probably a better way to do it, but this should work. 我不确定你要做什么,我怀疑可能有更好的方法,但这应该有效。

template <template <class> class T, class U>
class Foo {
    friend class T<U>;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM