c++ - 从模板类继承和调用模板函数时出错

标签 c++ templates gcc

我有一些正在修改的模板代码,但遇到了一个我无法解决的奇怪错误。我能够使用以下更简单(但毫无意义)的代码片段重现问题:

struct Widget
{
};

template <typename A>
class Foo
{
public:

    template <int numA>
    inline bool funcCall()
    {
        return numA > 0;
    }

    inline bool funcCallNoTemplate()
    {
        return false;
    }
};

template <typename B>
class Bar : public Foo<B>
{
public:

    // doesn't work
    bool concrete()
    {
        return Foo<B>::funcCall<5>();
    }

    // works fine
    bool other()
    {
        return Foo<B>::funcCallNoTemplate();
    }
};

int main()
{
    Bar<Widget> b;
    b.concrete();
    b.other();
    return 0;
}

我在 GCC 4.7 中遇到的错误如下(第 30 行是 Bar::concrete 的主体):

example.cxx: In member function ‘bool Bar<B>::concrete()’:
example.cxx:30: error: expected primary-expression before ‘)’ token
example.cxx: In member function ‘bool Bar<B>::concrete() [with B = Widget]’:
example.cxx:43:   instantiated from here
example.cxx:30: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’

似乎编译器甚至无法正确解析它,我是否遗漏了一些使该行完全虚假的东西?

最佳答案

It seems like the compiler can't even parse this correctly, am I missing something here that makes that line completely bogus?

是的。您需要使用 template消歧器:

return Foo<B>::template funcCall<5>();
//             ^^^^^^^^

这样你会告诉编译器解析依赖名称funcCall作为成员函数模板的名称,随后的尖括号作为相应模板参数的分隔符。

没有它,funcCall将被解析为数据成员的名称,而 <>将分别被解析为小于大于

关于c++ - 从模板类继承和调用模板函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16597775/

相关文章:

c++ - 自下而上的模板 MergeSort 迭代

c - C 中的指针更改以前的值

c - 检测宏参数是否为类型名

linux - 无法编译GCC,但没有给出具体错误

c++ - 是否可以使用指向函数类型的指针来专门化模板,这样它就可以分别看到该指针中使用的所有类型?

c++ - 为什么要这样调用宏?

c++ - 使用 Boost Asio 的快速数据(图像)传输服务器客户端

c++ - 为什么 boost::hana::overload_t 不能成为类的成员

c++ - 编译模板时无限循环

c++ - 如何为各种高度相似的类型创建通用函数?