C++ 声明指向C+中decltype为的方法的指针+;
C++ 声明指向C+中decltype为的方法的指针+;,c++,pointers,gcc,methods,clang,C++,Pointers,Gcc,Methods,Clang,clang和gcc之间存在一些差异。其中之一是如何处理方法的指针。给定以下代码: template <typename T_Class, typename T_Ret, typename ... Args> void store_method(T_Class *object, T_Ret (T_Class::*method)(Args ... args)); class SomeObjectWithPotentiallyLongName { int commonly_us
clang
和gcc
之间存在一些差异。其中之一是如何处理方法的指针。给定以下代码:
template <typename T_Class, typename T_Ret, typename ... Args>
void store_method(T_Class *object, T_Ret (T_Class::*method)(Args ... args));
class SomeObjectWithPotentiallyLongName {
int commonly_used_method(int var);
void register_method() {
/* The code below is okay for gcc with -std=gnu++11. But clang
* says:
* 'reference to non-static member function must be called' */
store_method(this, commonly_used_method);
/* To make this fine for clang (and also - gcc), I have to
* extend previous line as next */
store_method(this, &SomeObjectWithPotentiallyLongName::commonly_used_method);
}
}
但此代码会产生以下错误,即clang
:
'decltype(*this)'(也称为'SomeObjectWithPotentiallyLongName&')不是类、命名空间或枚举
有没有办法建立这样的宏?如果没有,还有其他方法解决这个问题吗?那么
T&
不是一个在这种情况下可用的类型(正如评论中指出的,它仍然是一个类型),它是一个参考。您可以使用std::remove_reference::type
()删除引用并获取T
类型:
typedef std::remove_reference<decltype(*this)>::type T;
宏中缺少
和。此外,还可能产生限定引用类型,因此您应该使用删除引用和限定符:
#define STORE_METHOD(method)\
store_method(\
this,\
&std::decay<decltype(*this)>::type::method\
)
T&
是一种类型。它可能不是您想要的类型,但它是一种类型。
T::method
#define STORE_METHOD(method)\
store_method(\
this,\
&std::decay<decltype(*this)>::type::method\
)
#define STORE_METHOD(method)\
store_method(\
this,\
&std::decay_t<decltype(*this)>::method\
)