pav*_*din 1 c++ inheritance templates g++ template-meta-programming
以免考虑以下代码:
#include <iostream>
template <typename T_VAL> // not used template argument
struct Foo { int x; };
template <typename T_VAL>
struct Bar { int x; };
template <typename T_VALUE>
struct A
{
// just 2 overloaded data() members:
virtual void data(Foo<T_VALUE>) {
std::cout << "FOO EMPTY\n";
}
virtual void data(Bar<T_VALUE>) {
std::cout << "BAR EMPTY\n";
}
};
template <typename T_VALUE>
struct B : public A<T_VALUE>
{
void data(Foo<T_VALUE>) {
std::cout << "smart FOO impl\n";
}
};
int main(void) {
B<float> TheObject;
Bar<float> bar;
TheObject.data(bar); // I expect virtual base call here
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器消息是:
tmpl.cpp: In function 'int main()':
tmpl.cpp:43:14: error: no matching function for call to 'B<float>::data(Bar<float>&)'
TheObject.data(bar);
^
Run Code Online (Sandbox Code Playgroud)
void data(Bar<T_VALUE>)- > void data(Bar<T_VALUE>&)不会改变任何东西
为什么派生类B没有虚拟空数据(Bar&)?
另一个data是隐藏的.
做
template <typename T_VALUE>
struct B : public A<T_VALUE>
{
using A<T_VALUE>::data; // Add this line
void data(Foo<T_VALUE>) {
std::cout << "smart FOO impl\n";
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43 次 |
| 最近记录: |