c++ - 匹配多种类型以进行模板特化解析

标签 c++ templates metaprogramming c++11

简单地忽略正常函数重载将更好地服务于此示例的事实。它只是作为学习模板编程的一种方式。话虽如此,欢迎您评论使用函数重载与函数模板特化相比的好处/差异(尽管这可能值得单独提出一个问题)。


考虑以下示例:

template <typename T>
inline void ToString(T value, char* target, size_t max_size );

template <>
inline void ToString<float>(float value, char* target, size_t max_size)
{
   snprintf( target , max_size , "%f" , value);
}

template <>
inline void ToString<double>(double value, char* target, size_t max_size)
{
    snprintf( target , max_size , "%f" , value);
}

有没有办法只编写一个同时匹配 floatdouble 类型的特化?

基本上,我设想为模板类型编写一个模板特化,该模板类型将同时匹配 floatdouble(作为“float or double”类型匹配器),但我'我不确定 C++ 是否完全可以做到这一点。也就是说,我以前曾亲眼目睹过意想不到的模板魔术,所以我认为在这里问这个问题是个好问题。

最佳答案

这是一个标准的解决方法:

#include <type_traits>
#include <cstdio>


// Helper class

template <typename T>
struct Printer
{
  static typename std::enable_if<std::is_floating_point<T>::value, int>::type
  print(T x, char * out, std::size_t n)
  {
    return std::snprintf(out, n, "%f", x);
  }
};

// Convenience function wrapper

template <typename T> int print(T x, char * out, std::size_t n)
{
  return Printer<T>::print(x, out, n);
}

void f()
{
  char a[10];

  Printer<double>::print(1.2, a, 10);  // use helper class
  print(1.4f, a, 10);                  // wrapper deduces type for you
}

如果您使用非 float 类型调用任一构造,则会出现编译时错误。请注意,这可能会错误地用于需要 %Lf 格式说明符的 long double;还记得当通过可变函数参数传递时, float 被提升为 double 值。

关于c++ - 匹配多种类型以进行模板特化解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7285975/

相关文章:

c++ - gcc 中 Unresolved 重载函数类型

ruby-on-rails - 动态定义关注的类和实例方法

Ruby - 与对象的特征类共享局部变量

c++ - 在标准 C++11 中获取剩余的可用内存?

c++ - "undefined reference to"错误。 (从成员函数到静态成员变量)

c++ 当 const 不是显式的?

C++ 模板和派生类

c++ - 访问违规读取位置 OpenCV Canny 函数

c++ - 使用默认参数的模板参数推导行为

ruby - 基本元编程 : extending an existing class using a module?