如果为false,std :: is_member_function_pointer不会编译

问题描述 投票:10回答:1

我在寻找:我有一个模板化的类,如果类具有所需的函数,则需要调用函数,例如:

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(),编译器也会失败,当然。

c++ typetraits if-constexpr
1个回答
17
投票

is_member_function_pointer没有检测到实体T::x的存在,它假定它确实存在并返回它是否是成员函数指针。

如果要检测它是否存在,可以使用detection idiom。例:

#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{});
}

live example on godbolt.org


我写了一篇关于检查不同C ++标准版本中表达式有效性的一般问题的文章:

"checking expression validity in-place with C++17"

© www.soinside.com 2019 - 2024. All rights reserved.