模板化类型的格式说明符

Nic*_*mer 1 c++ templates format-specifiers

我有一个在整数类型上模板化的C++类,例如,

template<typename int_type>
Run Code Online (Sandbox Code Playgroud)

比如那个类中的某个地方,我想用来sscanf从文件中读取一些值,例如,

int_type num_rows;
fgets( buffer, BUFSIZE, in_file );
sscanf( buffer, "%d", &num_rows);
Run Code Online (Sandbox Code Playgroud)

格式说明符仅int_type在内在函数时才能正常工作int.

是否有更好的方法来处理格式说明符int_type

hmj*_*mjd 7

而不是使用sscanf()和格式说明使用std::istringstream具有operator>>():

if (fgets( buffer, BUFSIZE, in_file ))
{
    std::istringstream in(buffer);
    if (!(in >> num_rows))
    {
        // Handle failure.
    }
}
Run Code Online (Sandbox Code Playgroud)

替换(未示出)FILE*和a std::ifstream将使得能够移除std::istringstream并且直接从std::ifstream相反地读取.