c++ - 根据模板类型启用模板类中的方法

标签 c++ boost template-meta-programming

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

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/

相关文章:

c++ - boost msm中的错误处理错误

c++ - 了解如何在编译时计算总和

c++ - 为什么概念不能传递给模板元函数?

c# - 使用托管 C++ 项目中的 C# 类

c++ - 如何编译 CLOGS 库

c++ - 使用两个对象作为 unordered_map 或替代方案的哈希键

c++ - 如何声明两个将彼此的签名作为参数的函数?

c++ - 将模板限制为仅某些类?

c++ - 继承层次结构中的特定类作为 boost::signals2 回调中的类型

c++ - RAII : Initializing data member in const method