c++ - 如果为 false,std::is_member_function_pointer 不会编译
问题描述
我在找什么:我有一个模板类,如果该类有想要的函数,我想调用一个函数,比如:
template<class T> do_something() {
if constexpr (std::is_member_function_pointer<decltype(&T::x)>::value) {
this->_t->x(); // _t is type of T*
}
}
会发生什么:T
如果不带函数,编译器不会编译。小例子:
#include <type_traits>
#include <iostream>
class Foo {
public:
void x() { }
};
class Bar { };
int main() {
std::cout << "Foo = " << std::is_member_function_pointer<decltype(&Foo::x)>::value << std::endl;
std::cout << "Bar = " << std::is_member_function_pointer<decltype(&Bar::x)>::value << std::endl;
return 0;
}
编译器说:
is_member_function_pointer.cpp:17:69: error: no member named 'x' in 'Bar'; did you mean 'Foo::x'?
std::cout << "Bar = " << std::is_member_function_pointer<decltype(&Bar::x)>::value << std::endl;
那么,std::is_member_function_pointer
当我不能在其中使用它时,它是if constexpr
什么?如果我只使用this->_t->x()
编译器,肯定也会失败。
解决方案
is_member_function_pointer
不检测实体的存在T::x
,它假定它存在并返回它是否是成员函数指针。
如果要检测它是否存在,可以使用检测成语。例子:
#include <experimental/type_traits>
template<class T>
using has_x = decltype(&T::x);
template<class T> void do_something(T t) {
if constexpr (std::experimental::is_detected<has_x, T>::value) {
t.x();
}
}
struct Foo {
void x() { }
};
struct Bar { };
int main() {
do_something(Foo{});
do_something(Bar{});
}
我写了一篇关于检查不同 C++ 标准版本中表达式有效性的一般问题的文章:
推荐阅读
- typescript - 如何在我的 Aurelia HTML 中显示与数组不同的对象?
- android - I/Ads:广告无法加载:1 在我的原生 android 项目中
- node.js - 为什么 NPM 运行测试命令因 npm ERR 而失败!代码生命周期错误?
- c++ - 函数参数的继承类和基类之间的 C++ const * 转换,
- scikit-learn - roc_auc_score, 'roc_auc', 'auc' 的奇怪行为
- linux - /dev/ttyUSB 延迟 15 毫秒
- r - 如何在 R 上对 COVID 进行 MCMC 推理
- python - 如何将 jinja 变量传递给我在 Flask 中创建的模板文件?
- java - 使用 JAVA API 从 Elastic Search Suggest Search 响应中提取源数据
- javascript - 如何在选项卡中呈现反应组件?