以函数作为模板参数的部分专用化拒绝

Partial specialization rejection with function as template argument

本文关键字:专用 拒绝 参数 函数      更新时间:2023-10-16

得到了这个代码,它曾经在以前版本的gcc上编译得很好:

template <int line, typename FuncSig, FuncSig f>
struct HelperWrapper;
// [...]
template <int line, typename Ret, Ret (&Func)()>
struct HelperWrapper<line, Ret (&)(), Func>
{
    static inline int WrapFuncT(const int)
    {
        return 0; // Changed
    }
};
// Unary
template <int line, typename Ret, typename Arg1, Ret (&Func)(Arg1)>
struct HelperWrapper<line, Ret (&)(Arg1), Func>
{
    static inline int WrapFuncT(const int)
    {
        return 1; // Changed
    }
};
// Binary
template <int line, typename Ret, typename Arg1, typename Arg2, Ret (&Func)(Arg1, Arg2)>
struct HelperWrapper<line, Ret (&)(Arg1, Arg2), Func>
{
    static inline int WrapFuncT(const int)
    {
        return 2; // Changed
    }
};

被 GCC 7.1.1 拒绝,并显示错误:

a.hpp:683:16: error: partial specialization 'struct Type::Implementation::HelperWrapper<line, Ret (&)(), Func>' is not more specialized than [-fpermissive]
     struct HelperWrapper<line, Ret (&)(void), Func>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a.hpp:640:16: note: primary template 'template<int line, class FuncSig, FuncSig f> struct Type::Implementation::HelperWrapper'
     struct HelperWrapper;
            ^~~~~~~~~~~~~
a.hpp:695:16: error: partial specialization 'struct Type::Implementation::HelperWrapper<line, Ret (&)(Arg1), Func>' is not more specialized than [-fpermissive]
     struct HelperWrapper<line, Ret (&)(Arg1), Func>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a.hpp:640:16: note: primary template 'template<int line, class FuncSig, FuncSig f> struct Type::Implementation::HelperWrapper'
     struct HelperWrapper;
            ^~~~~~~~~~~~~
a.hpp:707:16: error: partial specialization 'struct Type::Implementation::HelperWrapper<line, Ret (&)(Arg1, Arg2), Func>' is not more specialized than [-fpermissive]
     struct HelperWrapper<line, Ret (&)(Arg1, Arg2), Func>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a.hpp:640:16: note: primary template 'template<int line, class FuncSig, FuncSig f> struct Type::Implementation::HelperWrapper'
     struct HelperWrapper;

我不明白这条消息,因为据我了解,GCC 所说的主模板是代码中不存在的通用模板结构的前向声明。

此代码的思想是捕获传入函数的签名和参数类型。

1( 海湾合作委员会对吗?(如果您认为不是,请引用当前标准中支持您主张的内容(

2(我如何修复代码,以便它被GCC接受(它被Clang接受到VisualStudio 2003(。我不能使用 C++11。

编辑:我终于成功地向GCC开发人员报告了这个问题,这是一个应该在下一个版本中修复的错误。

这似乎是一个编译器错误,但在 GCC Bugzilla 上没有找到对此问题的任何引用。尽管如此,我还是像您一样在编译器资源管理器上使用最新的 GCC 编译器测试了您的代码,并且使用函数指针而不是函数引用也适用于 GCC 7.1。这是一个现场演示。


如果部分模板专用化不比主模板更专用,编译器可能会抱怨。但在这种情况下,GCC 是错误的,因为您将FuncSig模板参数专门化为函数引用 ( Ret (&)() (。更奇怪的事实是,编译器不会抱怨函数指针。

此外,问题的原因似乎不是FuncSig而是f模板参数。当我从主模板及其专用中删除f时,问题消失了:

template <int line, typename FuncSig>
struct HelperWrapper;
template <int line, typename Ret>
struct HelperWrapper<line, Ret (&)()> {
    static inline int WrapFuncT(const int) {
        return 0;
    }
};
/* ... */

在此处查看现场演示。