2012-02-19 127 views
0

我寫的模板整數包裝類,我想基於模板參數類型的類提供一個分配新建分配FY操作:在模板類啓用方法基於模板類型

template<typename IntType> 
class secure_int { 
public: 
    // enable only if boost::is_signed<IntType> 
    secure_int &operator=(intmax_t value) { 
    // check for truncation during assignment 
    } 

    // enable only if boost::is_unsigned<IntType> 
    secure_int &operator=(uintmax_t value) { 
    // check for truncation during assignment 
    } 
}; 

因爲運營商=不是成員模板,那麼帶有boost :: enable_if_c的SFINAE將不起作用。什麼是提供這種功能的工作選項?

回答

1

你可以把它變成一個成員模板,並默認參數在C++ 11中無效。如果您沒有支持該功能的編譯器,那麼專業化是您唯一的選擇。

+0

我這樣去看它是否是一個工作解決方案,但我的公司還沒有切換到C++ 11。 – kyku 2012-02-19 09:33:49

2

爲什麼不使用模板專業化?

template<typename IntT> 
struct secure_int {}; 

template<> 
struct secure_int<intmax_t> 
{ 
    secure_int<intmax_t>& operator=(intmax_t value) 
    { /* ... */ } 
}; 

template<> 
struct secure_int<uintmax_t> 
{ 
    secure_int<uintmax_t>& operator=(uintmax_t value) 
    { /* ... */ } 
};