C++ 中的两个模板:“‘>’标记之前预期的主表达式”[重复]

2024-04-08

最小工作示例:

#include <iostream>

struct Printer
{
    template<class T>
    static void print(T elem) {
        std::cout << elem << std::endl;
    }
};

template<class printer_t>
struct Main
{
    template<class T>
    void print(T elem) {
        // In this case, the compiler could guess T from the context
        // But in my case, assume that I need to specify T.
        printer_t::print<T>(elem);
    }
};

int main()
{
    Main<Printer> m;
    m.print(3);
    m.print('x');
    return 0;
}

我的编译器(g++)给了我错误“‘>’标记之前预期有主要表达式”。出了什么问题以及如何解决?

接受 C++11。


clang在这种情况下给出了更好的错误消息:

$ clang++     example.cpp   -o example
example.cpp:18:20: error: use 'template' keyword to treat 'print' as a dependent template name
        printer_t::print<T>(elem);
                   ^
                   template 
1 error generated.

只需添加template就在它说的地方,你就设置好了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 中的两个模板:“‘>’标记之前预期的主表达式”[重复] 的相关文章

随机推荐