c++ - match multiple types for template specialization resolution -


Summarize the fact that normal work overloading will provide this example better, this means only There is a way to know about template programming. You're welcome to comment on profits / differences by using a function overload compared to fashion template specialization, though (although it may ask a question of herself).


Consider the following example:

  template & lt; Typename T & gt; Inline zero toasting (T value, four * target, size_t max_size); Template & lt; & Gt; Inline Zero ToString & lt; Float & gt; (Float value, char * target, size_t max_size) {snprintf (target, max_size, "% f", value); } Template & lt; & Gt; Inline Zero ToString & lt; Double & gt; (Double value, four * target, size_t max_size) {snprintf (target, max_size, "% f", value); }   

Is these two attributes only match to float and double types? Actually I am writing a template specialization for a template type that matches float and double ( Like 'float or double type' type of music) but I am not sure whether it is possible with C ++, he said, I have seen unexpected template magic in front of my eyes, so I think it is here There is a good question to ask.

Here is a standard solution:

  #include & lt ; Type_traits & gt; # Include & lt; Cstdio & gt; // Assistant Class Template & lt; Typename T & gt; (Type printer) std :: enable_if & lt; Std :: is_floating_point & lt; T & gt; :: value, int & gt; :: print type (t x, four * out, std :: size_t n) {return std :: snprintf (outside, n, "% f", x); }}; // Feature Function Cover Template & lt; Typename T & gt; Int print (Tx, char * out, std :: size_t n) {return Printer & lt; T & gt; :: print (x, out, n); } Zero F () {four A [10]; Printer & lt; Double & gt; :: Print (1.2, A, 10); // Usage Assist Class Print (1.4 F, A, 10); // wrapper cut type for you}   

If you create with a non-floating type, you will get a compile-time error though be careful that it is a mistake for a long time Can work with, which requires the % Lf format specification; And also remember that float is promoted to doubles when passed through flacadic function arguments.

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -