C++特化调用模版类的模板方法

SEO#

  • how to call template function of template class
  • invalid operands of types unresolved overloaded function type

问题#

使用模版类的模版成员函数(方法)时会报错,而同样的函数放在普通类则正常编译。

复现#

template <typename T>
class Filter {
public:
    template <int N>
    void Update(const T& input)
    {
        // do my stuff
    }
};

Filter<float> f();
f.Update<2>(1.0f);

报错#

invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binaryoperator<’

似乎GCC错将特化函数f.Update<2>断句为f.Update<2导致运算符重载错误。

解决#

开始搜索的方向是GCC本身问题,关于断句的bug已经在GCC Bugzilla – Bug 60531提到并解决。
仔细搜索后发现这个:

Explicit qualification is required because of its setting can not be deduced. Without template we get a syntax error, which will be perceived < as the operator is less than....See also language author point of view in "13.6. Stroustrup, spec. edition. 935-936."

对于模版类的模版方法,特化时无法通过类的实例推断模版参数T因此需要显式使用template关键字,阻止GCC将<解释为小于号。
正确调用方法为

Filter<float> f();
f.template Update<2>(1.0f);

参考#

60531 – template function not resolved when comparing functions
c++ - Calling template function within template class - Stack Overflow

posted @   azureology  阅读(661)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示
主题色彩