0

我正在编写一个模板整数包装类,我想根据类的模板参数类型提供一个赋值运算符:

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 将不起作用。提供此类功能的工作选项是什么?

4

2 回答 2

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)
  { /* ... */ }
};
于 2012-02-19T07:48:18.967 回答
1

您可以将其制成成员模板,并在 C++11 中将参数默认为 void。如果您没有支持该功能的编译器,那么专业化是您唯一的选择。

于 2012-02-19T07:47:50.790 回答