具有不同参数的多态性 [英] Polymorphism with different parameters

查看:61
本文介绍了具有不同参数的多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使用具有相同参数的功能名称,具有不同参数的多态性?

By any chance is it possible to do polymorphism with the same name of function with different parameters?

例如,我希望这三个功能合而为一.

For example, I want those three functions to become one.

virtual bool isValid1(const std::string&) = 0;
virtual bool isValid2(const uint32_t&) = 0;
virtual bool isValid3(const int& num) = 0;

换句话说,我有一个Base A 和三个Derived A类.我也有Base B ,其中保存了Base A类和T(模板类型)的向量,可以是 string unit32 int )参数.当我想从Base B 调用 isValid 函数时,使用 vector 和参数(例如: isValid(argument))我有点卡住了,因为我必须事先知道是否要调用 isValid1(string) isValid2(uint32) isValid3(int).

In other words, I have a Base A and three Derived A class. I also have Base B that holds a vector of Base A class and a T(template type, could be a string, unit32 or int) argument. When I want to call from Base B the isValid function using the vector and argument (like this: isValid(argument)) I am a bit stuck, since I have to know before if to call isValid1(string), isValid2(uint32) or isValid3(int).

一些询问者的代码

template <class T>
class Field
{
public:
    void addValidator(BaseValidator* validator) { m_validator.push_back(validator); }
    void validate() const { m_validator[0].isValid(m_data);}
private:
    std::vector<BaseValidator*> m_validator;
    T m_data;
};

  • 我选择多态,但也欢迎其他类型的解决方案.
  • 如果问题太短而无法理解,请告诉我,因此我可以用其他方法重写.
  • 推荐答案

    您可以过载成员函数.即使它们是纯虚拟的并且应该被覆盖 1 :

    You can overload member functions. Even if they are pure virtual and meant to be overriden1:

    virtual bool isValid(const std::string&) = 0;
    virtual bool isValid(const uint32_t&) = 0;
    virtual bool isValid(const int& num) = 0;
    

    现在, isValid(argument)将执行重载解析并选择要调用的重载(通过动态调度).唯一的潜在问题是,对于某些参数,最后两个重载可能同样有效,因此重载可能是模棱两可的.但这确实取决于调用它的 T .

    Now isValid(argument) is going to do overload resolution and pick the overload to call (via dynamic dispatch). The only potential issue is that the last two overloads may be equally good for certain arguments, so the overloading could be ambiguous. But that really depends on the T in it's called on.

    1 -毕竟这就是访问的含义.

    1 - That's exactly what visitation is about, after all.

    这篇关于具有不同参数的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆