我正在编写一个模板整数包装器类,我想在其中提供一个基于该类模板参数类型的赋值运算符:
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
}
};
因为 operator= 不是成员模板,所以带有 boost::enable_if_c 的 SFINAE 将无法工作。提供此类功能的工作选项是什么?
最佳答案
为什么不使用模板特化?
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)
{ /* ... */ }
};
关于c++ - 根据模板类型启用模板类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9347582/