繁体   English   中英

返回类型匹配auto和friend功能

[英]Return type match with auto and friend function

所以我回答了这个问题: 定义类模板的友元函数模板 ,我从g ++(5.3)和clang(3.8)中发现了一些“怪异”的行为:

我们假设以下模板:

template<int M>
struct test {
private:
    int value;

    template<int U, int K>
    friend test<K> foo (test<U> const t);
};

template <int M, int N = 2 * M>
test<N> foo (test<M> const t) {
    test<N> r;
    r.value = t.value;
    return r;
}

int main(){
    test<1> t;
    foo(t);
}

这与两个编译器一起编译(如预期的那样 - 如果这不应该编译,请随意发表评论并解释原因)。

如果我改变了:

template<int U, int K>
friend auto foo(test<U> const t);

template <int M, int N = 2 * M>
auto foo (test<M> const t) { /* ... */ }

这用g ++编译但不用clang编译,如果我将一个设置为auto而另一个设置为特定值,例如:

template<int U, int K>
friend test<K> foo(test<U> const t);

template <int M, int N = 2 * M>
auto foo (test<M> const t) { /* ... */ }

// or:

template<int U, int K>
friend auto foo(test<U> const t);

template <int M, int N = 2 * M>
test<N> foo (test<M> const t) { /* ... */ }

两个编译器拒绝代码说:

错误:'int test <2> :: value'是私有的

我的两个相关问题是:

  • 哪种编译器适用于第一种情况( auto用于声明/定义)?
  • 为什么在定义函数时无法使用auto ,在声明友谊时test<K>

或者在一个问题中: 当在类外部定义函数时,关于auto for friend函数声明的规则是什么?

考虑[dcl.spec.auto] / 13

具有使用占位符类型的声明返回类型的函数或函数模板的重新声明或特化也应使用该占位符,而不是推导类型。

即如果朋友声明使用auto而第二声明不使用,则它们不匹配。 另一种方式是由核心问题2081保证。 最后,如果两者都使用auto ,声明应该按照[temp.over.link] / 6匹配,所以在这种情况下Clang是不正确的。

暂无
暂无

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

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