我明白如何声明一个函数的类型:怪异成员函数指针语法
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 technical paper我发现我不熟悉语法:
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 :: *'在模板参数中意味着什么。 –
对不起。没有得到它很快重新打开。 – NathanOliver
这不限于成员指针。如果你有'使用T = int()',那么'T * p'是有效的,而'int()* p'是语法规则所禁止的。 – cpplearner