C++ std::成员函数上有_函数吗?
我可以执行以下操作来检测某个对象是否为函数:C++ std::成员函数上有_函数吗?,c++,function,templates,std,C++,Function,Templates,Std,我可以执行以下操作来检测某个对象是否为函数: void f() { } int main() { std :: cout << std :: is_function <decltype(f)> :: value << std :: endl; // true } decltype(&myclass::f) 我该怎么办?我想要类似上面的东西。。好的,要只打印true您需要传递地址-它必须是指向成员函数的指针: void f() { } int
void f()
{
}
int main()
{
std :: cout << std :: is_function <decltype(f)> :: value << std :: endl; // true
}
decltype(&myclass::f)
我该怎么办?我想要类似上面的东西。。好的,要只打印
true
您需要传递地址-它必须是指向成员函数的指针:
void f()
{
}
int main()
{
std :: cout << std :: is_function <decltype(f)> :: value << std :: endl; // true
}
decltype(&myclass::f)
否则,语法将解析为引用静态函数-因此会出现错误。但是,
&myclass::f
不是一个函数-您不能只调用它(std::is\u function
将返回false
) 成员函数指针与普通函数指针不同。另外,myclass::f
格式错误,没有&
。对于成员函数,存在
#包括
#包括
类myclass
{
公众:
void f(){}
};
int main()
{
std::coutdecltype(myclass::f)
格式不正确
您可以使用(std::is\u member\u function\u pointer::value
)
有趣的是利用std::is_函数
,可以实现std::is_函数
:
template< class T >
struct is_member_function_pointer_helper : std::false_type {};
template< class T, class U>
struct is_member_function_pointer_helper<T U::*> : std::is_function<T> {};
template< class T >
struct is_member_function_pointer : is_member_function_pointer_helper<
typename std::remove_cv<T>::type
> {};
模板
结构是\成员\函数\指针\助手:std::false \类型{};
模板
struct is_member_function_pointer_helper:std::is_function{};
模板
结构是成员函数指针:是成员函数指针<
typename std::remove_cv::type
> {};
myclass::f
应该是函数调用,但是没有提供参数,这会导致编译器错误
您可以使用运算符&
获取成员函数的地址,例如&myclass::f
,但它是成员函数指针,将返回false
检查T是否为函数类型。std::function、lambdas、带有重载运算符()的类和指向函数的指针等类型不算作函数类型
您可以使用来检查它是否是非静态成员函数指针。在C++17中,您可以使用helper函数std::is\u member\u function\u pointer\u v
#include <iostream>
#include <type_traits>
struct A {
int fun() const&;
};
int main()
{
std::cout << std::is_member_function_pointer_v<decltype(&A::fun)> << '\n';
}
#包括
#包括
结构A{
int fun()常量&;
};
int main()
{
这确实是一个过多的间距。
#include <iostream>
#include <type_traits>
struct A {
int fun() const&;
};
int main()
{
std::cout << std::is_member_function_pointer_v<decltype(&A::fun)> << '\n';
}