這是可能的:模板參數不fulfulling所有要求
struct A {
//void f(); < not declared in struct A
};
template<typename T>
struct Wrapper {
T t;
void call_f() { t.f(); }
};
int main() {
Wrapper<A> w;
}
這編譯罰款,只要w.call_f()
不叫。 w.call_f()
無法實例化,因爲A::f
不存在。
我在與被不同T
類型,這並不總是實現接口部分全部採用這種包裝的模板的情況。 (主要是爲了避免代碼重複)。
這不起作用:
struct A {
//using i_type = int; < not declared/defined
};
template<typename T>
struct Wrapper {
using its_i_type = typename T::i_type;
// compile error, even if `i_type` gets never used
};
int main() {
Wrapper<A> w;
}
沒有做到這一點:
struct A {
//using i_type = int; < not declared/defined
};
template<typename T>
struct Wrapper {
typename T::i_type call_f() { return 0; }
// does not compile, even if `call_f()` is never instantiated
};
int main() {
Wrapper<A> w;
}
是否有處理這些情況的好方法,沒有大量重複的代碼(如專門爲Wrapper
,等等。)?
以及如何對一個'call_f'返回'i_type'? – aschepler
@aschepler,那麼它會失敗。在這種情況下,我將使'call_f'成爲模板成員函數,或者我將使用'type_trait'類的解決方案,這將涉及專業化 – WhiZTiM
*「您有兩個選項[..] 1. [.. ] 2。[..] 3。[..]「* :-)(我知道,多個編輯)。 – Jarod42