[英]C++ class template inheritance and operator =
我有一個從模板類派生的“可分配”對象。 但是,即使明確定義了類型,該對象的賦值運算符也沒有正確調用。
#include "stdio.h"
template <bool any>
struct Base {
void operator = ( const Base& arr ) { printf("base = base\n"); }
};
// definition in advance
template <bool any> struct Assignable_A;
template <bool any>
struct A : public Base<any> {
Assignable_A<any> operator [] (int i) { Assignable_A<true> b; return b; }
};
template <bool any>
struct Assignable_A : public A<any> {
template <bool other>
void operator = ( const A<other>& a ) { printf("Assignable_A = A<other>\n"); }
template <bool other>
void operator = ( const Assignable_A<other>& b ) { printf("Assignable_A = Assignable_A<other>\n"); }
};
int main() {
A<true> a;
a[1] = a; // Assignable_A<true> = A<true>
a[1] = a[0]; // Assignable_A<true> = Assignable_A<true>
return 0;
};
我想編碼輸出
Assignable_A = A<other>
Assignable_A = Assignable_A<other>
然而,實際輸出是
Assignable_A = A<other>
base = base
為什么在第二次調用中沒有調用Assignable_A::operator =
? (用 g++ 7.3.0 編譯)
從copy_assignment (強調我的):
類 T 的復制賦值運算符是名稱為
operator=
的非模板非靜態成員函數,它只接受一個類型為T
、T&
、const T&
、volatile T&
或const volatile T&
。
和
如果沒有為類類型(結構、類或聯合)提供用戶定義的復制賦值運算符,編譯器將始終將其聲明為類的內聯公共成員。
所以你的模板operator=
不是復制賦值,所以編譯器生成一個。
要獲得預期的結果,您必須提供:
void operator = ( const Assignable_A& b ) { // Assignable_A<any>
printf("Assignable_A = Assignable_A<other>\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.