jag*_*mue 10 c++ type-traits if-constexpr
我正在寻找的是:我有一个模板化的类,如果该类具有所需的函数,则想调用一个函数,例如:
template<class T> do_something() {
if constexpr (std::is_member_function_pointer<decltype(&T::x)>::value) {
this->_t->x(); // _t is type of T*
}
}
Run Code Online (Sandbox Code Playgroud)
发生的情况:如果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;
}
Run Code Online (Sandbox Code Playgroud)
编译器说:
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;
Run Code Online (Sandbox Code Playgroud)
那么,std::is_member_function_pointer当我不能在其中使用它时,它有if constexpr什么用呢?如果我只是使用this->_t->x()编译器,那么肯定也会失败。
Vit*_*meo 17
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{});
}
Run Code Online (Sandbox Code Playgroud)
我写了一篇关于在不同的C ++标准版本中检查表达式有效性的一般问题的文章:
| 归档时间: |
|
| 查看次数: |
265 次 |
| 最近记录: |