std :: is_member_function_pointer如果false不会编译

std::is_member_function_pointer does not compile if false

本文关键字:false 如果 编译 function is member std pointer      更新时间:2023-10-16

我要寻找的内容:我有一个模板类,如果类具有通缉函数,则想调用功能,例如:

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"

检查表达式有效性。
相关文章: