首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用派生类型重载函数的替代方法

使用派生类型重载函数的替代方法
EN

Stack Overflow用户
提问于 2017-02-25 07:43:16
回答 1查看 273关注 0票数 0

很抱歉标题内容不多,我真的不知道该怎么称呼我所问的内容。

我希望实现以下目标:拥有一个具有派生类型实例的基类类型的容器,访问容器并调用依赖于所访问的派生对象的类型的函数重载。在之前的一个问题中,我问了here,我了解到,到目前为止,我脑海中的静态设计不起作用。我尝试的方法是:

代码语言:javascript
复制
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重载,但是这不会编译,因为在编译时还不知道x0x1到底有哪种类型。但是,有没有其他设计可以实现这种行为呢?

EN

回答 1

Stack Overflow用户

发布于 2017-02-25 07:51:41

重载是一种基于静态类型的静态机制。

如果你想根据对象的动态类型动态地改变行为,C++提供了另一个内置的语言特性:虚函数。像这样使用它们:

代码语言:javascript
复制
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_fInt2Type<1>::do_f

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42450128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档