很抱歉标题内容不多,我真的不知道该怎么称呼我所问的内容。
我希望实现以下目标:拥有一个具有派生类型实例的基类类型的容器,访问容器并调用依赖于所访问的派生对象的类型的函数重载。在之前的一个问题中,我问了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到底有哪种类型。但是,有没有其他设计可以实现这种行为呢?
发布于 2017-02-25 07:51:41
重载是一种基于静态类型的静态机制。
如果你想根据对象的动态类型动态地改变行为,C++提供了另一个内置的语言特性:虚函数。像这样使用它们:
struct Int2TypeBase
{
virtual void do_f() = 0;
};
template <int v> struct Int2Type : Int2TypeBase
{
void do_f() override
{
// specific behaviour for Int2Type<v> goes here
}
/* ... */
};
void f(Int2TypeBase & x) { x.do_f(); }现在,您可以在任何基本子对象上调用f,并在运行时选择正确的行为。特别是,f(x0.get())和f(x1.get())现在分别在运行时选择和分派到Int2Type<0>::do_f和Int2Type<1>::do_f。
https://stackoverflow.com/questions/42450128
复制相似问题