如何在專用和非專用版本的C++類之間共享代碼?在專用和非專用模板結構之間共享代碼
這裏是什麼,我試圖完成一個人爲的例子:
#include <iostream>
using namespace std;
template <size_t n> struct Y {
int one() { return 1; }
int two();
};
template <> struct Y<1> {
int one() { return 11; }
int two();
};
template <size_t n> int Y<n>::two() { return one() * 2; }
int main() {
Y<1> X;
cout << X.one();
cout << X.two();
return 0;
}
這種失敗在鏈接時使用:
Undefined symbols for architecture x86_64:
"Y<1ul>::two()", referenced from:
_main in test-7c4ebe.o
但是,如果我改變Y<1> X;
到Y<2> X;
,編譯成功正好。
我在這裏的目標是使用two()
的示例實現來獲取該類的專用版和非專用版。
我能解決這個問題,繼承,像這樣:
#include <iostream>
using namespace std;
struct mixin {
virtual int one() = 0;
int two() { return one() * 2; }
};
template <size_t n> struct Y : public mixin {
int one() { return 1; }
};
template <> struct Y<1> : public mixin {
int one() { return 11; }
};
int main() {
Y<1> X;
cout << X.one();
cout << X.two();
return 0;
}
但我認爲,招致每次調用不必要的V-表查找到Y<n>.two()
,對不對?
有什麼辦法可以在專用和非專用版本之間共享代碼,而不會濫用繼承並引發v表查找調用?
define *濫用* in傳承。 – SergeyA
@SergeyA在我看來,這種問題應該是可以解決的,根本不需要繼承,儘管如果有一些解決方案使用繼承,但是避免了v-table查找,那就沒問題。 –
@SergeyA:好的,我誤解了。 – AnT