假设我们有一个模板:
template <class T>
void VeryImportantFunction(T t) {
// something
}在某个地方,它是这样调用的:
// ..
int a = 12345;
VeryImportantFunction(a);
// ..这是一个非常大的项目,有大量的源代码,并且在代码的某个地方偶尔会出现一个带有重载函数的新的头文件:
void VeryImportantFunction(int t) {
// totally another behavior
}并且上面的代码片段将调用重载函数,因为它具有更高的优先级。
我们能以某种方式禁用或以另一种方式禁用可能重载我们重要模板的编译时检测函数吗?
发布于 2018-04-26 17:57:06
你的问题不清楚,但这是我对它的看法。
如果想要重载模板,可以通过显式指定模板参数来调用该函数:
int a = 12345;
VeryImportantFunction<int>(a);如果你想让这种情况在将来再次发生,那就让VeryImportantFunction成为一个lambda或者struct --它们不能被“外部”重载:
inline const auto VeryImportantFunction = [](auto x){ /* ... */ };
// no one can overload this!如果你想知道没有外部工具的VeryImportantFunction的所有重载,那么以一种完全错误的方式调用它-编译器错误可能会显示所有考虑过的重载:
VeryImportantFunction(5, 5, 5, 5);
// error... will likely show all candidates发布于 2018-04-26 17:58:19
写
inline void VeryImportantFunction(int t)
{
VeryImportantFunction<int>(t); // call the template function
}紧跟在您的模板定义之后。
然后,如果有人编写了他们自己版本的void VeryImportantFunction(int t),您将得到一个编译器错误。
https://stackoverflow.com/questions/50039981
复制相似问题