【发布时间】:2019-03-02 19:50:57
【问题描述】:
我以为会调用具有最具体匹配参数类型的函数重载,但是当模板和继承类型结合时,我似乎不了解类型推导的一个方面。
例子:
#include<iostream>
#include<typeinfo>
struct Foo {};
struct Bar : Foo {};
#ifdef FOO
void print_typeid( const Foo& f ) {
std::cout << "(F) typeid: " << typeid(f).name() << std::endl;
}
#endif // FOO
#ifdef GENERIC
template<typename Generic>
void print_typeid( const Generic& g ) {
std::cout << "(G) typeid: " << typeid(g).name() << std::endl;
}
#endif // GENERIC
int main( int argc, char *argv[] ) {
Foo foo; print_typeid(foo);
Bar bar; print_typeid(bar);
return 0;
}
测试用例
1.仅定义 FOO
$ g++ -DFOO main.cpp -o foo && ./foo
输出:
(F) typeid: 3Foo
(F) typeid: 3Foo
这对我来说很有意义,因为对象 foo 和 bar 可能是
作为const Foo& 传递,并且由于没有编译时向下转换,
bar 必须标识为具有 Foo 类型。
2。仅定义 GENERIC
$ g++ -DGENERIC main.cpp -o generic && ./generic
输出:
(G) typeid: 3Foo
(G) typeid: 3Bar
这也是有道理的,因为foo 和bar 都是左值,可以传递给接受通用常量引用的函数。这将打印每个对象的实际类型。
3.定义 FOO 和 GENERIC
$ g++ -DFOO -DGENERIC main.cpp -o both && ./both
输出:
(F) typeid: 3Foo
(G) typeid: 3Bar
这个让我很困惑。已经确定两个对象都可以传递给这两个函数,我预计因为const Foo& 是bar 的更具体的兼容类型,所以我们会得到与案例 1 相同的输出。为什么会发生这种情况?
使用 gcc 7.2 和 clang 4 测试
【问题讨论】:
标签: c++ templates inheritance template-argument-deduction type-deduction