Any*_*orn 13 c++ overloading function
我很无聊,想出了这样的黑客(伪代码):
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(...);
Run Code Online (Sandbox Code Playgroud)
在真实的代码中使用它是邪恶的吗?
我可能的使用场景是例如数组元素的产品,可能会/可能不会溢出:
int size(short *array);
short size(short *array);
Run Code Online (Sandbox Code Playgroud)
如果使用模板,则可以从函数参数推断函数的原因,而不是模板参数
我宁愿使用模板专业化,只是感觉不那么"hacky",可能会更快(没有对象创建,当然,当然可以通过智能编译器进行优化).
但无论如何,我宁愿看到类似的代码
template<typename T> T function();
template<> int function() {
return 1;
}
template<> float function() {
return 1.0;
}
....
int a = function<int>();
float b = function<float>();
Run Code Online (Sandbox Code Playgroud)
但是你的代码没有任何问题,特别是如果你远离数字类型/指针,因为否则可能会出现意想不到的影响,转换规则在C++中非常复杂.