c++ - 使用类检查方法是否存在
问题描述
我正在尝试创建一个类型特征来执行编译时检查是否存在具有类类型的方法。下面是我实现的。我不确定为什么它不起作用。
T = 检查方法的类型。
R = 方法的返回类型。
P = 方法的参数类型。
template<typename T, typename R, typename P>
struct HasBarImpl {
template<typename> static std::false_type Test(...);
template<typename U>
static auto Test(P* p) ->
std::enable_if_t<std::is_same_v<decltype(declval(U).Bar(p)), R>, std::true_type>;
static constexpr bool value = std::is_same<decltype(Test<T>(nullptr)), std::true_type>::value;
};
template<typename T, typename R, typename P>
constexpr bool HasBar = HasBarImpl<T, R, P>::value;
struct Foo {
void Bar(int*) {}
};
TEST_CASE("Check for method's existence") {
bool r = false;
if constexpr (HasBar<Foo, void, int>) {
r = true;
}
CHECK(r == true); // Fails
}
解决方案
推荐阅读
- mysql - 将不同的独立过滤器应用于 GROUP BY 中的同一列
- string - 使用参数扩展字符串替换的换行符的 printf 解释
- javascript - 将 CSS 规则应用于两个其他元素之间的一组元素
- caching - 如何防止 Laravel 5.8 缓存控制器
- mysql - 如何正确擦除数据库并重新导入?
- excel - 关于在excel中将日期格式化为文本的问题
- wordpress - WordPress帖子未显示内部图像
- javascript - 如何通过单击按钮甚至传单中的标记来制作使我的菜单打开的按钮
- oracle - 仅使用 sqlplus 上传二进制(BLOB)内容的最有效方法是什么
- excel - 如何一次删除一个动态添加的用户窗体控件?