在 C++ 中使用模板专门化
如何使用模板专业化编写一个具有 2 种不同输入类型和输出类型的函数:
template <class input1, class input2, class output>
并返回 2 个数字(整数/双精度)的总和。但是,如果我得到 2 个整数,我想返回整数类型,但对于整数和双精度数的任何其他组合,我将始终返回双精度数。
我试图在不直接使用“+”运算符的情况下做到这一点,而是使用下一个函数:
double add_double_double(double a, double b) {return (a+b);}
double add_int_double(int a, double b) {return ((double)(a)+b);}
int add_int_int(int a, int b) {return (a+b);}
How can I write a function using template specialization that has 2 different input types and an output type:
template <class input1, class input2, class output>
and return the sum of the 2 numbers (integers/doubles). However, if I get 2 integers I want to return an integer type but for any other combinations of integer and double I'll always return double.
I am trying to do that without using directly the '+' operator but having the next functions instead:
double add_double_double(double a, double b) {return (a+b);}
double add_int_double(int a, double b) {return ((double)(a)+b);}
int add_int_int(int a, int b) {return (a+b);}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你可以使用 C++0x,你可以这样做:
If you can use C++0x, you could do this:
不要使用模板专门化。请改用重载。专门化函数很复杂并且很少需要:
当且仅当两个参数都是 int 时才会调用第二个版本;否则,将调用第一个版本。
Don’t use template specialization. Use overloading instead. Specializing functions is complicated and rarely needed:
The second version will be called if and only if both arguments are
int
; otherwise, the first version will be called.函数模板的返回类型可能取决于模板参数的类型。在您的情况下,您可以执行类似以下操作:
我认为在本例中实际上并不需要对 ret_t 的显式转换,但它演示了更多技术。
这仅处理整数,但这个想法可以很容易地推广到处理更复杂的情况。
It is possible for the return type of a function template to depend on the types of the template parameters. In your case, you can do something similar to:
I don't think the explicit casts to
ret_t
are ever actually needed in this case, but it demonstrates some more of the technique.This handles just ints, but the idea can easily be generalized to handle more complex cases.
这可能是您所需要的:
结果:
This might be what you need:
Result:
您问题的答案位于C++ 模板一书的第15章。本章有一个累加器示例来解决您的问题。本章接下来将讨论升级特征,其中它将解决添加两种不同类型的问题,并解决类型升级的问题。
The answer to your question lies in Chapter 15 of C++ templates book. This chapter has an accumulator example which addresses your question. Further down the chapter it will talk about promotion traits where it will address the problem of adding two different types and also address type promotion.