【问题标题】:C++ call template function of class as template parameter [duplicate]C ++调用类的模板函数作为模板参数[重复]
【发布时间】:2023-09-07 23:24:02
【问题描述】:

我有错误“'int'之前的预期主表达式”和“预期';'在这段代码中的“int”之前,有人知道为什么吗?

struct cpu
{
    template<class T> static void fce() {}
};

template<class _cpu>
struct S
{    
    void fce() 
    {  
        _cpu::fce<int>(); //error: expected primary-expression before 'int'
                          //error: expected ';' before 'int'
    }
};

int main()
{
    S<cpu> s;
    s.fce();
}

【问题讨论】:

  • 试试 _cpu::template fce();将 fce 视为依赖模板名称。
  • @0x499602D2 更好的回答哈哈

标签: c++ templates compiler-errors


【解决方案1】:
_cpu::template fce<int>(); 

试试上面的。

由于 _cpu 是 template 参数,编译器无法识别 fce 可能是 member function 的名称 - 因此它将 &lt; 解释为小于符号。 为了让编译器识别函数模板调用,添加template量词:

【讨论】: