指向成员函数语法的怪异指针 [英] Weird pointer to member function syntax
问题描述
我了解如何声明函数的类型:
I understand how to declare the type of a function:
typedef void (typedef_void_f)(); // typedef_void_f is void()
using alias_void_f = void(); // alias_void_f is void()
它可以用来声明函数指针:
And it can be used to declare function pointers:
void function() { std::cout << __PRETTY_FUNCTION__ << '\n'; }
typedef_void_f *a = function; // pointer to void()
alias_void_f *b = function; // pointer to void()
对于成员函数指针,语法稍微复杂一些:
For member function pointers the syntax is slightly more complicated:
struct S { void function() { std::cout << __PRETTY_FUNCTION__ << '\n'; } };
typedef void (S::*typedef_void_m_f)();
using alias_void_m_f = void (S::*)();
typedef_void_m_f c = &S::function; // pointer to S void() member function
alias_void_m_f d = &S::function; // pointer to S void() member function
这是我对C ++中的函数指针的理解,我认为就足够了.
This is my understanding of function pointers in C++ and I thought that it was enough.
但是在 p0172r0技术论文中我发现了一种我不熟悉的语法:
But in the p0172r0 technical paper I've found a syntax that I'm not familiar:
struct host {
int function() const;
};
template <typename TYPE>
constexpr bool test(TYPE host::*) { // <---- What is this??
return is_same_v<TYPE, int() const>;
}
constexpr auto member = &host::function;
test(member);
据我所了解的代码,test
函数从函数所属对象的类型中分离出函数的类型,因此在模板test
函数中TYPE
模板参数为void()
,但是如果我尝试以下操作:
As I understand the code, the test
function splits the type of the function from the type of the object where the function belongs, so in the template test
function the TYPE
template parameter would be void()
but if I try the following:
void my_test(void() S::*) {}
my_test(&S::function);
我遇到一堆语法错误:
error: variable or field 'my_test' declared void
void my_test(void() S::*) {}
^
error: expected ')' before 'S'
void my_test(void() S::*) {}
^
error: 'my_test' was not declared in this scope
my_test(&S::function);
很明显,我不了解p0172r0的test
函数语法.
So is obvious that I'm not understanding the p0172r0's test
function syntax.
有人可以解释template <typename TYPE> constexpr bool test(TYPE host::*)
语法的详细信息吗?
Can someone explain the details of the template <typename TYPE> constexpr bool test(TYPE host::*)
syntax?
推荐答案
TYPE host::*
是指向类数据成员的指针. TYPE
是类成员的类型,host::*
表示指向host
成员的指针.因此TYPE host::*
接受一个指向host
TYPE host::*
is a pointer to a class data member. TYPE
is the type of the class member and host::*
means pointer to member of host
. So TYPE host::*
accepts a pointer to any of member of host
这篇关于指向成员函数语法的怪异指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!