繁体   English   中英

在 c++ 中同时处理 static 和非 static 函数

[英]Handling both static and non static functions in c++

我有一个 c++ class,它的部分定义是:

template <class InputClass>
class MyClass

InputClass被定义为 MyClass 的子 class:

class InputClass: public MyClass<InputClass>

MyClass 中有很多地方都有这个调用:

InputClass::AttributeName()

其中AttributeName()在 InputClass 的不同子类上定义为:

static std::string AttributeName

然而,最近,有 InputClass 的特定子 class,我们必须将属性名称定义为非 static,因为我们希望这个新子 class 的不同实例不共享AttributeName名称):

std::string AttributeName

我可以进行哪些修改,以便我仍然可以AttributeName()作为 static 或MyClass内部的非静态变量?

老实说,我看不出如何在派生类中创建 static 和具有相同名称的非静态成员函数,并在基础 class 中区分它们。 另外,我不知道是否有办法调用非静态成员 function,该成员在派生的 class 中声明,但未在基础 class 中声明。

If we omit those two requirements, then you could check whether the static function exists and call it, or fallback to a non-static (virtual) function otherwise (in my example I replaced your AttributeName function with static_name and name for static and non-相应的静态函数):

#include <string>
#include <iostream>
#include <utility>
#include <experimental/type_traits>

template<class InputClass>
class Item {

    virtual std::string name() {
        return "none";
    };
    ...
public:
    virtual ~Item() = default;
    
    ...   
};

class DerivedNonStatic: public Item<DerivedNonStatic> {
    std::string name() final {
        return "non-static item";
    }
};

class DerivedStatic: public Item<DerivedStatic> {
public:
    static std::string static_name() {
        return "static item";
    }
};

现在,在基本Item class 中,您可以决定使用哪个 function,如下所示:

class Item {
    
    template<typename T>
    using static_name_t = decltype(T::static_name); // static member function type
    static constexpr bool has_static_name = std::experimental::is_detected_v<static_name_t, InputClass>;

    void printName() {
        if constexpr(has_static_name) {
            std::cout << InputClass::static_name() << std::endl;
        } else {
            std::cout << this->name() << std::endl;
        }
    };
    ...
}

以及如何在客户端代码中使用它:

int main() {
    DerivedNonStatic dns;
    dns.printName(); // prints "non-static item"

    DerivedStatic ds;
    ds.printName(); // prints "static item"
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM