【问题标题】:format specification for template parameters模板参数的格式规范
【发布时间】:2014-09-20 09:18:11
【问题描述】:

我有一个以整数类型为模板的 C++ 类;类似于

template<typename int_type>
void myClass(int_type a) {
// [...]
}

我现在想用sscanf() 将文件中的数据读入int_type 类型的变量中。为此,我必须指定int_type格式。到目前为止,我正在做类似的事情

if(sizeof(int) == sizeof(int_type))
  sscanf(buffer, "%d %d", &i, &j);
else if(sizeof(long long) == sizeof(int_type))
  sscanf(buffer, "%lld %lld", &i, &j);
else
  assert(false);

但这似乎不是处理事情的最佳方式。

还有其他建议吗?

【问题讨论】:

  • 最好使用绑定到std::istringstreamoperator&lt;&lt;() 的模板版本,而不是sscanf()
  • sizeof(int) == sizeof(unsigned int),但%d 不是unsigned int 的正确格式说明符(例如,考虑INT_MAXUINT_MAX 之间的那些数字)。要为不同的类型提供不同的实现,函数重载通常是一个不错的方法。

标签: c++ templates format-specifiers


【解决方案1】:

你可以使用一个类和专业化:

template <typename T> struct scanf_format;

template <> struct scanf_format<int>
{
    static constexpr const char* format = "%d";
    static constexpr const char* format2 = "%d %d";
};

template <> struct scanf_format<long long>
{
    static constexpr const char* format = "%lld";
    static constexpr const char* format2 = "%lld %lld";
};

然后像这样使用它

template <typename T>
void my_scanf(const char* buffer, T&a, T&b)
{
    sscanf(buffer, scanf_format<T>::format2, &a, &b);
}

但更简单的方法是使用operator &gt;&gt;

template <typename T>
void my_scanf2(const char* buffer, T&a, T&b)
{
    std::stringstream ss(buffer);
    ss >> a >> b;
}

Live example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多