【发布时间】:2016-01-27 17:12:39
【问题描述】:
我了解如何声明函数的类型:
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::*在模板参数中的含义。 -
很抱歉。没有得到它很快重新打开。
-
这不仅限于成员指针。如果你有
using T = int(),那么T* p是有效的,而int()* p是语法规则禁止的。 -
@cpplearner 是的,正如我在谈论的p0172r0 paper 中已经指出的那样。
标签: c++ function-pointers member-function-pointers