Consider this situation: We write code that works well until we include a header file that happens to have an function overloading one of our original functions. In this case, there maybe some places where the calling of function goes to the overloaded version for better fitting of parameters, which is also logically unexpected. What's worse, compiler doesn't complain.
考虑这种情况:我们编写的代码运行良好,直到我们包含一个头文件碰巧有一个函数重载我们的原始函数之一。在这种情况下,可能会有一些地方调用函数进入重载版本以更好地拟合参数,这在逻辑上也是意料之外的。更糟糕的是,编译器不会抱怨。
Here is a demo to clarify my question:
这是一个演示来澄清我的问题:
/*
For simlicity, I write the codes in different files in this way;
Whether include header.h behaves differently
*/
// main.cpp
#include "header.h" // If included, sb will be overloaded
#include<iostream>
void sb(int){std::cout << "int" << endl;}
int main(){
sb(3.5);
return 0;
}
// header.h
void sb(double);
// hehe.cpp
void sb(double){cout << "double" << endl;}
I have no idea whether this problem happens frequently or not, and wonder if there is any way to solve or prevent it.
我不知道这个问题是否经常发生,并想知道是否有任何方法可以解决或阻止它。
1 个解决方案
#1
0
The simple method is to never let the overloads be a better match. The less simple (but more scalable) method is to apply some organisation to your program, either classes, namespaces or just better function names.
简单的方法是永远不要让重载更好地匹配。不太简单(但可扩展性更强)的方法是将一些组织应用于您的程序,无论是类,命名空间还是更好的函数名。
Simple example:
void sb(double);
void sb(int){std::cout << "int" << endl;}
int main(){
sb(static_cast<int>(3.5));
return 0;
}
Less simple (but more scalable)
不太简单(但更具伸缩性)
namespace some_namespace { // could be a class
void sb(double);
}
namespace other_namespace { // also could be a class
void sb(int){std::cout << "int" << endl;}
}
int main(){
other_namespace::sb(3.5);
return 0;
}
#1
0
The simple method is to never let the overloads be a better match. The less simple (but more scalable) method is to apply some organisation to your program, either classes, namespaces or just better function names.
简单的方法是永远不要让重载更好地匹配。不太简单(但可扩展性更强)的方法是将一些组织应用于您的程序,无论是类,命名空间还是更好的函数名。
Simple example:
void sb(double);
void sb(int){std::cout << "int" << endl;}
int main(){
sb(static_cast<int>(3.5));
return 0;
}
Less simple (but more scalable)
不太简单(但更具伸缩性)
namespace some_namespace { // could be a class
void sb(double);
}
namespace other_namespace { // also could be a class
void sb(int){std::cout << "int" << endl;}
}
int main(){
other_namespace::sb(3.5);
return 0;
}