Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"expected initializer before `<' token" with inline template function in global namespace

Tags:

templates

g++

I am trying to compile some code, in one of my headers I have the following function in the global namespace:

template <class T>
inline
T
to_type<T> (const std::string& string)
{
    std::stringstream ss(string);
    T value;
    ss >> value;
    return value;
}

Yet somehow, this throws the g++ error expected initializer before '<' token (I changed one of the quotes to solve a conflict with the SO formatting)

I don't understand this error. Why is to_type not a valid initializer? This is the first time this symbol has been used. How do I fix this snippet?

like image 913
robrene Avatar asked Oct 08 '22 15:10

robrene


1 Answers

The correct syntax is

template <class T>
inline
T
to_type(const std::string& string)
{
    std::stringstream ss(string);
    T value;
    ss >> value;
    return value;
}

(note no <T> after to_type).

<> are only put after the name of the function (or class) being declared when declaring a specialization, not when declaring the base template.

like image 82
ymett Avatar answered Oct 11 '22 13:10

ymett