std :: is_member_function_pointer如果false不会编译
std::is_member_function_pointer does not compile if false
我要寻找的内容:我有一个模板类,如果类具有通缉函数,则想调用功能,例如:
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;
那么,当我无法在if constexpr
中使用它时,std::is_member_function_pointer
是什么?如果我只使用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{});
}
godbolt.org上的实时示例
我写了一篇文章,内容涉及在不同的C 标准版本中检查表达式的有效性的一般问题:
"使用C 17"
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- C++如果使用 lambda 表达式的语句返回 true,但输出来自 false,为什么
- 如果数组中有重复的数字,如何返回'false'?
- 如果BOOL仅从false到true一次,我可以避免锁定布尔
- `如果constexpr(false)`始终评估为true
- 如果语句计算结果为 false,即使条件为真
- std :: is_member_function_pointer如果false不会编译
- 如果任何条件是错误的,如何从for循环中返回false
- 为什么如果条件为false,为什么仍会对语句进行辩护
- true/false功能如果存在总和
- 如果模板的错误代码在If(false)中,我必须专门化模板吗
- 我正在尝试创建一个函数,如果一个元素在向量中,则返回 true/false,但我收到错误
- 如果要删除的项目不在列表中,如何返回"false"
- 如果删除,如何返回 true,如果不使用 bool,则返回 false
- 如果数据类型为整数值或双数值,则当c++返回true/false时
- 如何编写一个c++代码,使函数在初始参数为大写时返回true,如果不是,则返回false
- 如果某个条件语句中的某些内容导致该条件语句不再为true/false,则该语句是否停止执行
- 如果是字符或字符串返回false,但如果输入不能转换为整数则返回true.c++的while循环
- 如果语句不求值为false?程序给出奇怪的输出.为什么
- OpenCV如何获得bool true,如果图像是' == '和false,如果不是