Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two templates in C++: "expected primary-expression before ‘>’ token" [duplicate]

Tags:

c++

templates

Minmal working example:

#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;
}

My compiler (g++) gives me the error "expected primary-expression before ‘>’ token". What's wrong and how to fix it?

C++11 accepted.

like image 405
Johannes Avatar asked Dec 20 '22 05:12

Johannes


1 Answers

clang gives a better error message in this case:

$ 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.

Just add the template where it says to, and you're set.

like image 189
Carl Norum Avatar answered Dec 24 '22 02:12

Carl Norum