【问题标题】:Format specifier for templated type模板类型的格式说明符
【发布时间】:2013-04-10 14:54:09
【问题描述】:

我有一个以整数类型为模板的 C++ 类,例如,

template<typename int_type>

假设在那个类的某个地方,我想使用sscanf 从文件中读取一些值,例如,

int_type num_rows;
fgets( buffer, BUFSIZE, in_file );
sscanf( buffer, "%d", &num_rows);

格式说明符仅在 int_type 是内在 int 时才能正常工作。

有没有更好的方法来处理一般int_type 的格式说明符?

【问题讨论】:

  • 这并不是真正的模板化... sscanf with %d 仅适用于整数,因此模板化类型在这里并不重要。您还需要更改 scanf 参数
  • 你可以有一个私有静态成员函数,它返回char const *,并为你打算支持的每个不同的int_type专门化它,并使用返回值作为sscanf()的格式参数。

标签: c++ templates format-specifiers


【解决方案1】:

不要使用sscanf() 和格式说明符,而是使用std::istringstreamoperator&gt;&gt;()

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

std::ifstream 替换(未显示)FILE* 将启用删除std::istringstream 并直接从std::ifstream 读取。

【讨论】:

    【解决方案2】:

    您可以在您的类中声明 fmt 并在实现中为每种类型提供显式值:

    // foo.hpp
    template< typename T >
    class foo
    {
    private:
        static const char* fmt;
    
    public:
        void print() const
        {
            T num_rows;
            fgets( buffer, BUFSIZE, in_file );
            sscanf( buffer, fmt, &num_rows);
        }
    };
    

    // foo.cpp
    template<> const char* foo< int >::fmt = "%d";
    template<> const char* foo< long >::fmt = "%ld";
    

    【讨论】:

      【解决方案3】:

      您可以创建模板助手类:

      template<class int_type>
      struct fmt_helper_f{};
      
      template<>
      struct fmt_helper_f<int>
      {
        static const char * fmt() {return "%d";}
      };
      
      template<>
      struct fmt_helper_f<float>
      {
        static const char * fmt() {return "%f";}
      };
      

      实际上,您可能希望使用流进行输入和输出

      【讨论】:

        猜你喜欢
        • 2012-11-06
        • 1970-01-01
        • 2020-05-23
        • 1970-01-01
        • 2023-03-10
        • 2020-10-07
        • 1970-01-01
        • 2017-11-23
        • 1970-01-01
        相关资源
        最近更新 更多