我了解如何声明函数的类型:
typedef void (typedef_void_f)(); // typedef_void_f is void()
using alias_void_f = void(); // alias_void_f is void()
它可以用来声明函数指针:
void function() { std::cout << __PRETTY_FUNCTION__ << '\n'; }
typedef_void_f *a = function; // pointer to void()
alias_void_f *b = function; // pointer to void()
对于成员函数指针,语法稍微复杂一些:
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++中函数指针的理解,我认为这就足够了。
但在p0172r0 技术论文 http://open-std.org/JTC1/SC22/WG21/docs/papers/2015/p0172r0.html我发现了一个我不熟悉的语法:
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
功能splits函数的类型来自函数所属对象的类型,因此在模板中test
函数TYPE
模板参数将是void()
但如果我尝试以下操作:
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);
很明显我不理解 p0172r0test
函数语法。
有人可以解释一下详细信息吗template <typename TYPE> constexpr bool test(TYPE host::*)
syntax?