match multiple types for template specialization resolution

后端 未结 1 667
情歌与酒
情歌与酒 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 
    #include 
    
    
    // Helper class
    
    template 
    struct Printer
    {
      static typename std::enable_if::value, int>::type
      print(T x, char * out, std::size_t n)
      {
        return std::snprintf(out, n, "%f", x);
      }
    };
    
    // Convenience function wrapper
    
    template  int print(T x, char * out, std::size_t n)
    {
      return Printer::print(x, out, n);
    }
    
    void f()
    {
      char a[10];
    
      Printer::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)
提交回复
热议问题