![](/img/trans.png)
[英]Is it possible to declare a template function with 'auto' return type as a friend of a class?
[英]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函數聲明的規則是什么?
具有使用占位符類型的聲明返回類型的函數或函數模板的重新聲明或特化也應使用該占位符,而不是推導類型。
即如果朋友聲明使用auto
而第二聲明不使用,則它們不匹配。 另一種方式是由核心問題2081保證。 最后,如果兩者都使用auto
,聲明應該按照[temp.over.link] / 6匹配,所以在這種情況下Clang是不正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.