加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

一个涉及非平凡模板和朋友声明的C语法问题

发布时间:2020-12-16 10:16:17 所属栏目:百科 来源:网络整理
导读:以下代码应该是自解释的.我有两个关于使用语法的问题(这是必须使用的语法).如果你能为这些提出的问题提供答案,我将永远感激不尽. template typename Tstruct A { template typename S void f (const AS s); template typename S friend struct A; // Questio
以下代码应该是自解释的.我有两个关于使用语法的问题(这是必须使用的语法).如果你能为这些提出的问题提供答案,我将永远感激不尽.

template <typename T>
struct A {
    template <typename S>
    void f (const A<S> &s);

    template <typename S>
    friend struct A; 
    // Question 1: why isn't the syntax 'friend struct A<S>' ? 
    // The semantic would stay,since we would like A<S> (for ANY S) to be friend of every A<T>..

    private:
        void g () const {}
};

template <typename T> 
template <typename S> // Question 2: Why can't the syntax be 'template <typename T,typename S>' ?
void A<T>::f (const A<S> &s) {
    s.g();
}

int main () {
    A<bool> abool;
    A<char> achar;

    abool.f(achar);
}

我已经确认这确实是唯一正确的语法(我很乐意发现我错了).我的问题更多的是关于语法背后的推理,正如问题的主体所解释的那样.

谢谢你的帮助.

解决方法

why isn’t the syntax …

Why can’t the syntax be …

你期望我们说什么?无论谁决定这种语法(主要是Stroustrup本人,AFAIK)都认为他们的语法比你的语法更好.

哪一个更好或更容易记住我不知道 – 但我确实发现它们比你的更有意义.当然,你可以自由地不同意.

编辑:好的,Alexander has nicely answered question #2.关于#1:

不同之处在于A< S>.命名一个类型,这是函数参数所期望的类型,而A本身就是一个模板的名称,从中创建类型,如果你想成为一个模板而不是一个类型,这是有意义的:

template <typename S>
void f (const A<S> &s); // A<S> being the name of a type

template <typename S>
friend struct A; // A being the name of a template

您可以与特定模板实例建立联系,而不是整个模板,但为此,模板必须已经由朋友声明中的编译器(即声明)知道:

template< typename T >
class foo;

class bar {
  friend class foo<int>; // foo<int> being the name of a specific instance of foo
};

所以交换模板是一个例外(“通常的”朋友声明声明一个函数或类)并且确实需要不同的语法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读