没有在clang++中编译带有指针到方法的嵌套模板类

Nested template classes with pointer-to-method not compiled in clang++

本文关键字:方法 嵌套 指针 clang++ 编译      更新时间:2023-10-16

我的问题的SSCCE是:

template <class T> class MyClass
{
  template <void (MyClass::*M)() const> struct wrapper
  {
    virtual void call();
  };
};
template <typename T>
template <void (MyClass<T>::*M)() const>
void MyClass<T>::wrapper<M>::call()
{
}

此代码在gcc中编译,但错误失败:

error: nested name specifier 'MyClass<T>::wrapper<M>::' for declaration does not refer into a class, class template or class template partial specialization
void MyClass<T>::wrapper<M>::call()
 ~~~~~~~~~~~~~~~~~~~~~~~~~^

在叮当声+ +。为什么?

在类调用定义解决了问题,我知道。任何非指针方法模板在任何地方都可以正常工作。使用模板/typename进行实验没有结果。

可能的解决方法:考虑使用std::function代替wrapper。它不完全相同(对可接受的函数指针的限制较少),但它可以在clang++上编译并简化您的代码。

#include <functional>
template <class T> class MyClass
{
    typedef std::function<void(void) const > wrapper;
};

您可以在类定义中移动方法的实现:

template <class T> class MyClass
{
    template <void (MyClass::*M)() const> struct wrapper
    {
        virtual void call(){/* move implementation here */};
    };
};