我明白如何聲明一個函數的類型:怪異成員函數指針語法
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