如果模板值可转换为布尔值,则在编译时禁用类方法
Disable class method at compile time if template value is castable to a bool
如果类中包含的类型T
可以转换为布尔值,我想禁用此类上的 no-arg 方法。
我一直在用enable_if
尝试一些SFINAE的东西,但是我遇到了很多问题。我想要的可能吗?
template <typename T>
struct Watch {
T t;
// Enable if and only if bool(t) can be performed
void stop() {
// ...
}
void stop(int secondsFromNow) {
// ...
}
};
int main() {
Watch<int> watch;
watch.stop();
watch.stop(5);
Watch<string> watchStr;
//watchStr.stop();
watchStr.stop(2);
}
在阅读了许多关于使用 SFINAE 和模板隐藏内容的堆栈溢出帖子后,我一直无法让其他东西为我工作。
如果有人尝试调用Watch
上不可转换为布尔值的元素,如何在不影响任何其他方法的情况下使在编译时调用stop()
失败?
在这种情况下---当您想根据类的模板参数而不是函数本身的参数从重载解析中删除函数时---正确的习惯是将签名的实例化推迟到使用默认参数调用函数的点:
template <typename U = T, typename = std::enable_if_t<std::is_convertible_v<U, bool>>>
void stop();
在这里,在调用stop
并U
被赋予值之前,不会尝试计算enable_if
类型,因此 SFINAE 启动。
在某些情况下,您可能只是希望在不满足编译时条件时根本不声明函数。可以通过从包含或不包含相关函数的 CRTP 基类继承来实现此目的。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何访问由共享指针保存的类方法?
- 将子类方法声明为基类的友元
- 我的模板类方法返回错误类型?
- Qt将信号与另一个类方法连接
- 给定基类方法的编译时重写
- 从 ObjC 代码调用 .mm 类方法时编译错误
- 如果模板值可转换为布尔值,则在编译时禁用类方法
- 类方法上的const编译错误
- 类方法子集的编译时生成
- 编译时找不到c++类方法
- C++程序在两台不同的机器上编译.共享库在一个上正常工作.另一方面,类方法返回NULL
- c++编译问题;类方法