代码之家  ›  专栏  ›  技术社区  ›  Georg Fritzsche

在编译时区分c++中的静态和非静态方法?

  •  1
  • Georg Fritzsche  · 技术社区  · 17 年前

    我目前的解决方案是有一个基类,它有一个方法which()和一个全局函数which((),如果不在对象的上下文中,应该使用它。 然而,这不适用于静态成员函数,在这里编译器更喜欢非静态方法而不是全局方法。

    class IdentBase
    {
    public:
      Ident(const std::string& id) _id(id) {}
      const std::string& which() const { return _id; }
    private:
      const std::string _id;
    };
    
    const std::string& which() { static const std::string s("bar"); return s; }
    
    #define ident() std::cout << which() << std::endl
    
    class Identifiable : public IdentBase
    {
    public:
      Identifiable() : Ident("foo") {}
      void works() { ident(); }
      static void doesnt_work() { ident(); } // problem here
    };
    

    3 回复  |  直到 17 年前
        1
  •  0
  •   Dan Hook    17 年前

    定义一个函数模板,为所有类型返回默认标识符。

    template<typename T>
    const std::string& which(const T& object)
    { static const std::string s("bar"); return s; }
    

    class IdentBase
    {
    public:
        IdentBase(const std::string& id): _id(id) {}
        const std::string& id() const { return _id; }
    private:
        const std::string _id;
    };
    
    template<>
    const std::string& which(const IdentBase& object)
    { return object.id(); }
    

    通过传递要标识的实例来调用函数模板。

    int main()
    {
        int i;
        std::cout << which(i) << std::endl;
    
        IdentBase foo("foo");
        std::cout << which(foo) << std::endl;
    
        return 0;
    }
    
        2
  •  1
  •   Chin Huang    17 年前

    您或许可以使用 is_member_function_pointer

        3
  •  0
  •   Alan    17 年前

    您是否需要像示例中那样为每个类的每个实例提供不同的标识符,或者您只是试图识别跟踪中的哪个类?

    将which()函数和_id成员更改为static会将它们都暴露给静态成员函数,并且会减少内存使用。

    推荐文章