C ++返回类型重载攻击 [英] C++ return type overload hack
问题描述
我很无聊,想出了这样的黑客(伪代码):
I was bored and came up with such hack (pseudocode):
1 struct proxy {
2 operator int(); // int function
3 operator double(); // double function
4 proxy(arguments);
5 arguments &arguments_;
6 };
7
8 proxy function(arguments &args) {
9 return proxy(args);
10 }
11 int v = function(...);
12 double u = function(...);
是否真的可以在实际代码中使用?
is it evil to use in real code?
我可能的使用场景是例如数组元素的产物,它可能/可能不会溢出:
my possible usage scenario is for example product of array elements, which may/may not overflow:
int size(short *array);
short size(short *array);
在使用模板的情况下,模板参数的原因可以从函数参数
The reason for function, in case you use templates, than template parameters can be inferred from function arguments
推荐答案
我宁愿使用模板专门化,只是感觉较少hacky,可能会更快
I'd rather use template specialization, just feels less "hacky" and probably will be faster (no object creation, although of course that can be optimized away by smart compiler).
但是无论如何,我宁愿看到像
But anyway, I'd rather see code like
template<typename T> T function();
template<> int function() {
return 1;
}
template<> float function() {
return 1.0;
}
....
int a = function<int>();
float b = function<float>();
你的代码没有什么问题,特别是如果你远离数值类型/指针,因为其他意外的效果可能会发生,转换规则在C ++中是相当复杂的。
Nothing wrong with your code though, especially if you stay away from numeric types/pointers since otherwise unanticipated effects might occur, rules of conversion is quite complicated in C++.
这篇关于C ++返回类型重载攻击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!