2012-07-01 53 views
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 
    // ... 
} 
+0

你的目標是使用默認的構造函數,如果沒有構造函數參數? –

回答

5

使用is_constructible

template <typename T, typename A> 
typename std::enable_if<std::is_constructible<T, A>::value, T*>::type create(A i) 
{ 
    return new T(i); 
} 

template <typename T, typename A> 
typename std::enable_if<!std::is_constructible<T, A>::value, T*>::type create(A i) 
{ 
    return new T(); 
} 
+0

如果你的供應商不支持'std :: is_constructible',但你得到了'decltype',那麼如果你說'ctor(int)'或者只是無參數' ctor案? –