使用VC++ 2010,给出以下内容:
class Base { };
class Derived : public Base { };
template<class T> void foo(T& t); // A
void foo(Base& base); // B
Derived d;
foo(d); // calls A
foo(static_cast<Base&>(d)); // calls B
Run Code Online (Sandbox Code Playgroud)
我想在上面调用"B".我可以用演员来实现这一点Base,但为什么这是必要的?
我希望为所有不是从Base(内置类型等)派生的类型调用模板函数,但我希望从派生类型调用非模板重载Base,而不需要客户端显式转换.我也尝试使重载成为模板的特化,但在这种情况下会发生相同的行为.得到我正在寻找的东西的惯用方法是什么?
c++ templates overloading type-constraints implicit-conversion
C++标准是否保证以下内容?:
template<typename T>
void function(T (&)[1]);
template<typename T>
void function(T*);
int a[1];
function(a); // first function gets called, not second version
Run Code Online (Sandbox Code Playgroud) 抱歉标题不清楚,如果找到更好的标题,请随时编辑.在正常功能和模板功能之间的优先级中已经深入讨论了相关主题,但我没有找到我的问题的答案.
我的代码是:
template<typename T>
void f(T t){std::cout << "Template 1" << std::endl;} // template 1
template<typename T, typename B>
void f(T t){std::cout << "Template 2" << std::endl;} // template 2
int main () {
f(1); // line 1, template 1 will be called
f<int>(1); // template 1 will be called
f<int,int>(1); // template 2 will be called
}
Run Code Online (Sandbox Code Playgroud)
在第1行调用模板1函数的可能原因是什么?它在规范中是否定义明确?
在第1行,我认为编译器应该给出"模糊过载"错误.
请考虑以下代码:
#include <iostream>
using namespace std;
void fun(const char* s){
if (s == nullptr) {
puts("const char* nullptr");
} else {
printf("%s\n", s);
}
}
template <typename T>
void fun(T* p){
printf("%p\n", p);
}
int main() {
int a;
fun("abc"); // Resolves to fun(const char*)
fun(&a); // Specializes the template to int*
fun(nullptr); // Uses fun(const char*)??
fun(NULL); // Same as above
}
Run Code Online (Sandbox Code Playgroud)
我很诧异g++ 7.2.0也不会抛出不明的重载解析错误,因为我认为nullptr并NULL可以融入任何指针类型,其中包括fun(int*)专门从模板,只要不是专门用于过载std::nullptr_t.
为什么 …