【发布时间】:2017-07-15 23:07:41
【问题描述】:
对不起,标题信息不充分,我真的不知道我在问什么。
我想实现以下目标:拥有一个带有派生类型实例的基类类型容器,访问容器并根据访问的派生对象的类型调用函数重载。在我之前问过here 的一个问题中,我了解到到目前为止我想到的静态设计不起作用。我试过的方法是这样的:
struct Int2TypeBase{
};
template <int v>
struct Int2Type : public Int2TypeBase
{
enum
{
value = v
};
};
void f(const Int2Type<0>&){
std::cout << "f(const Int2Type<0>&)" << "\n";
}
void f(const Int2Type<1>&){
std::cout << "f(const Int2Type<1>&)" << "\n";
}
int main(){
using namespace std;
std::vector<std::reference_wrapper<Int2TypeBase>> v;
Int2Type<0> i2t_1;
v.emplace_back(i2t_1);
Int2Type<1> i2t_2;
v.emplace_back(i2t_2);
auto x0 = v[0];
auto x1 = v[1];
f(x0.get()); // After my imagination this would have called void f(const Int2Type<0>&)
f(x1.get()); // After my imagination this would have called void f(const Int2Type<1>&)
}
好的,所以我希望选择正确的 f 重载,但是这不会编译,因为在编译时不知道 x0 和 x1 实际上有哪种类型。但是是否有一些替代设计可以实现这种行为?
【问题讨论】:
标签: c++ polymorphism derived-class overloading