match multiple types for template specialization resolution

后端 未结 1 675
情歌与酒
情歌与酒 2021-01-17 17:15

Briefly dismiss the fact that normal function overloading will serve this example better. It is meant only as a way to learn about template programming. Having said that

相关标签:
1条回答
  • 2021-01-17 17:31

    Here's a standard solution idiom:

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

    You'll get a compile-time error if you call either construction with a non-floating type. Beware though that this might erroneously work for long doubles, which require the %Lf format specifier; and also recall that floats get promoted to doubles when passed through variadic function arguments.

    0 讨论(0)
提交回复
热议问题