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 编译的必要性,同时它可以像 gcc 一样整洁和清晰。
最明显的方法是编写一些宏,将 this
和 method_name
转换为类似 &TypeOfThis::method_name
的内容。
我的想法是使用decltype
:
#define STORE_METHOD(method) store_method(this, (decltype(*this))::method)
void SomeObjectWithPotentiallyLongName::register_method() {
STORE_METHOD(commonly_used_method);
}
但此代码会产生以下错误并带有 clang
:
'decltype(*this)' (aka 'SomeObjectWithPotentiallyLongName &') is not a class, namespace, or enumeration
有什么方法可以构建这样的宏吗?如果没有,是否有其他方法可以解决此问题?
最佳答案
嗯T &
不是在此上下文中可用的类型(正如评论中指出的那样,它仍然是一种类型),它是一个引用。您可以使用 std::remove_reference<...>::type
( documentation ) 删除引用并获取 T
改为输入:
typedef std::remove_reference<decltype(*this)>::type T;
然后使用:
T::method
关于c++ - 在 C++ 中使用 decltype 声明指向方法的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674545/