3
考慮兩個模板功能如下:模板SFINAE與構造
template <typename T, typename A>
T* create(A i) {
return new T(i);
}
template <typename T, typename A>
T* create(A i) {
return new T();
}
它們具有相同的簽名,但可以在給定T和A.
只有一次實例化是否有應用一些SFINAE方式習慣上述模板函數,以便當且僅當T具有接受A作爲參數類型的構造函數時,纔可實例化的模板函數的版本是第一版本,否則例如具有默認構造函數的第二版本將被實例化:
// S is given, cannot be changed:
struct S {
S(int) {}
}
int main() {
// the first template function should be instantiated since S has S(int)
create<S, int>(0); // the only call in the program
// ...
}
你的目標是使用默認的構造函數,如果沒有構造函數參數? –