5

我正在尝试编译一些代码,在我的一个头文件中,我在全局命名空间中有以下函数:

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

然而不知何故,这会引发 g++ 错误expected initializer before '<' token(我更改了其中一个引号以解决与 SO 格式的冲突)

我不明白这个错误。为什么to_type不是有效的初始化程序?这是第一次使用这个符号。如何修复此代码段?

4

1 回答 1

4

正确的语法是

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

(注意<T>后面没有to_type)。

<>只放在声明特化时声明的函数(或类)的名称之后,而不是在声明基本模板时。

于 2012-06-06T09:21:49.230 回答