基于模板类型启用模板类中的方法

Enabling methods in template class based on template type

本文关键字:方法 于模板 类型 启用      更新时间:2023-10-16

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

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++11中将参数默认为void。如果您没有支持该功能的编译器,那么专业化是您唯一的选择。