【问题标题】:Is it possible to mark an alias template as a friend?是否可以将别名模板标记为朋友?
【发布时间】:2015-11-06 09:26:50
【问题描述】:

想象一下我们有这样的代码:

template <class, class>
class Element
{};

template <class T>
class Util
{
public:
   template <class U>
   using BeFriend = Element<T, U>;
};

是否可以将BeFriend 标记为好友? (Util,或任何其他类)。

 编辑

尝试了“明显”的语法,但在 Clang 3.6 中都失败了。

template <class> friend class BeFriend;
template <class> friend BeFriend;

我不知道第二种语法,但found it in this answer。它似乎对 模板别名有效(并且是必需的),但在这种别名模板化的情况下没有帮助。

注意:正如一些人可以从最小示例中推断出的那样,我正在寻找一种方法来解决 C++ 不允许与部分模板特化成为朋友的限制)

【问题讨论】:

  • 试试看(剧透警告:你可以)
  • @bolov:使用哪种语法?我在 Clang 3.6 上尝试了 template &lt;class&gt; friend class BeFriendtemplate &lt;class&gt; friend BeFriend 都没有成功,所以更多的细节在这里会有很长的路要走:)
  • 我说得太早了。我认为这是微不足道的。我的错。
  • 如果有办法,委员会不知道。请参阅CWG 1554底部的注释。
  • 悲伤的答案就是答案,据我所知 - 在标准的相关条款中有明确(足够)的措辞可以成为朋友,而别名模板不在那里,所以这看起来像一个死胡同。但是,如果您愿意更改定义 Element 的方式,则可能存在针对您的潜在问题(模拟部分专业化朋友)的解决方法 - 这将涉及嵌套类模板。不确定它是否会帮助你。看起来like this

标签: c++ templates c++11 friend template-aliases


【解决方案1】:

我认为你不能这样做,因为部分特化不能被声明为朋友。

来自标准,[temp.friend]/7

友元声明不得声明部分特化。 [ 示例:

template<class T> class A { };
class X {
  template<class T> friend class A<T*>; // error
};

——结束示例]

您必须指定更通用的版本,例如:

template <class, class> friend class Element;

或完整的指定版本,例如:

using BeFriend = Element<T, int>;
friend BeFriend;

【讨论】:

    【解决方案2】:

    问题不在于别名,问题在于 “部分特化不能被声明为朋友”

    template <class, class> friend class Element;        // OK
    
    template <class, class> friend class Element<T, T>;  // Error
    

    【讨论】:

      猜你喜欢
      • 2010-09-17
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 2015-05-15
      • 2013-09-28
      • 1970-01-01
      相关资源
      最近更新 更多