我知道如何声明函数的类型:
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技术论文中,我发现了一种我不熟悉的语法:
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()
,但如果我尝试以下操作: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
函数语法。有人能解释一下template <typename TYPE> constexpr bool test(TYPE host::*)
语法的细节吗?
T::*
是什么意思。 - PaperBirdMasterusing T = int()
,那么T* p
是有效的,而int()* p
被语法规则禁止。 - cpplearner