基于模板类型启用模板类中的方法
Enabling methods in template class based on template type
我正在编写一个模板整数包装类,我想在其中提供一个基于类的模板参数类型的赋值运算符:
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。如果您没有支持该功能的编译器,那么专业化是您唯一的选择。
相关文章:
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- C++11:模板方法的模板函数调用无法编译?
- 类成员函数参数列表是否可以依赖于模板参数?
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 用c++中的纯虚拟方法抽象模板类
- 依赖于模板的错误
- 将 c++ 类成员函数专用于模板类
- C++ 使函数调用依赖于模板参数
- 派生对象调用的 Base 方法的模板推导
- 从部分专用模板方法调用模板非静态方法
- 将方法作为模板化参数传递 C++11
- c ++如何将模板应用于模板类的孩子/朋友?
- 如何修复"没有依赖于模板参数的参数'glGenVertexArrays'......"C++ 中的错误
- 不满足需要静态模板方法的模板模板概念的约束
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- C++复杂类型的单一方法的模板专用化
- 模板化类和模板化方法的模板专用化语法
- 如何使用类型专用化模板方法,该类型本身就是一个模板,其中只有返回类型依赖于模板类型
- 仅专用于模板类的一个方法(部分)
- 避免多个不依赖于模板类型的函数的模板瞬时的优雅方法