2012-07-07 117 views
2

這是怎麼回事?enable_if和構造函數

我認爲這應該工作時使用啓用,如果???

幫助??

不應該排除第二個構造函數嗎?

#include <iostream> 
#include <boost/type_traits.hpp> 
#include <boost/utility/enable_if.hpp> 



template<class T> 
class integral_holder{ 
public: 
integral_holder(T value_, typename boost::enable_if_c< boost::is_integral<T>::value>::type* ignore = 0) : value(value_){ 
    std::cout << "Integral" << std::endl; 
} 

integral_holder(T value_, typename boost::enable_if_c< boost::is_floating_point<T>::value>::type* ignore = 0) : value(floor(value_)){ 
    std::cout << "Floating point" << std::endl; 
} 

private: 
    T value; 

};

int main(int argc, const char * argv[]) 
{ 

    integral_holder<int> a(22); 

    return 0; 
} 

回答

4

當了類模板,並在構造函數的這個過程聲明生成的類實例化(不theiry身體,而只是他們的「簽名」),該enable_if類型是無效的,你會得到一個編譯器錯誤。

您需要使enable_if類型取決於構造函數的模板參數(使其成爲函數模板)。你的目標是可行的,因爲當你使用觸發SFINAE情況的構造函數時,在推導出函數模板參數類型時會形成無效類型。

+0

你能舉個例子嗎? – 2012-07-07 14:15:21

+0

模板 類integral_holder { 公共: 模板 integral_holder(U VALUE_,類型名的boost :: enable_if_c <提高:: is_integral ::值> ::類型*忽略= 0); template integral_holder(U value_,typename boost :: enable_if_c :: value> :: type * ignore = 0); 私有: T值; }; – 2012-07-07 14:21:14

+0

@BlairDavidson,這是正確的。 – 2012-07-07 21:35:21