模板参数的格式规范

format specification for template parameters

本文关键字:格式 参数      更新时间:2023-10-16

我有一个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);

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

还有其他建议吗?

您可以使用类和专业化:

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 >>

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

实例