模板成员函数不能显式专用

Template member function cannot be explicitly specialized

提问人:TStancek 提问时间:10/31/2023 最后编辑:HolyBlackCatTStancek 更新时间:11/2/2023 访问量:115

问:

我在类中有一个函数的声明

class A { 
  template<typename T, typename... ARGS>
  void Func( ARGS&&... args) {
     //DoSomeWork
  }
};

然后尝试将其专门用于此类类型

template<>
void A::Func<int>(bool arg) {
//DoSomeOtherWork
}

我收到错误

错误 C2910:“A::Func”:无法显式专用

有没有办法使模板专用化,或者我必须找到解决方法?如果没有办法对模板进行专业化,为什么会这样呢?

C ++14 可变 C++ 模板

评论

4赞 HolyBlackCat 10/31/2023
MSVC 只是无济于事。Clang 说,替换为使其工作,包括在 MSVC 上。error: no function template matches function template specialization 'Func'note: candidate template ignored: could not match 'ARGS &&' against 'bool'boolbool &&
0赞 TStancek 10/31/2023
是的,谢谢。既然你提到了它,我记得我很久以前就处理过这个问题。当可变参数模板的格式为 ARGS&&...时,参数必须为 '&&' 或 'const &'。你能添加你的评论作为答案吗?
0赞 user12002570 10/31/2023
同样的问题和解决方案:专门化可变参数模板成员函数时的问题
1赞 Hovercraft Full Of Eels 11/1/2023
这个问题正在 meta 上讨论

答:

1赞 HolyBlackCat 10/31/2023 #1

专用化无法更改参数类型。如果(主模板)通过引用接受参数,则专用化也必须这样做,例如:Func

template<>
void A::Func<int>(bool &&arg) {}

在这种情况下,MSVC 也无济于事。Clang 做得更好:

<source>:9:9: error: no function template matches function template specialization 'Func'
    9 | void A::Func<int>(bool arg) {
      |         ^
<source>:3:8: note: candidate template ignored: could not match 'ARGS &&' against 'bool'
    3 |   void Func( ARGS&&... args) {
      |        ^