c++ - 在 C++ 中使用 decltype 声明指向方法的指针

标签 c++ pointers gcc methods clang

clanggcc 之间有一些区别。其中之一是他们如何处理指向方法的指针。给定以下代码:

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 一样整洁和清晰。

最明显的方法是编写一些宏,将 thismethod_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/

相关文章:

c++ - 我写了一个C++程序来模拟Enigma机器,但没有得到输出

c++ - 从逗号分隔的文本文件中创建有意义数据 vector 的最佳方法是什么

c - Linux 中 timersub() 函数的隐式声明 - 我必须定义什么?

c++ - 为什么一个类方法在其对象文件中不存在而其他方法存在?

c++ - 在 C 中模拟 std::bind

C 将字符串文字与返回字符指针的函数进行比较

c - 阵列到结构类型转换

C++ 为每个元素调用任意函数

c++ - constexpr 上下文中 std::array 指针的 size()

c - 从目标文件中提取一个部分以分隔 .o