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

标签 c++ templates macros static-methods

对于一些用于识别实例的跟踪自动化,我想调用:

  • 返回其标识符的包含对象的非静态方法
  • 总是返回相同 id 的其他东西

我目前的解决方案是让基类有一个方法 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
};

我能否以某种方式避免使用变通方法,例如静态成员函数的特殊宏(可能使用一些模板魔术)?

最佳答案

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

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;
}

关于c++ - 在编译时区分 C++ 中的静态和非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1439959/

相关文章:

c++ - 类型检测 : using variadic arguments to properly implement a function that calculates the mean

c++ - c宏扩展错误

macros - 评估宏形式的参数

c++ - 如何在 SDL 中同时播放多个 MP3 文件?

java - 是否可以在所有操作系统上运行带有 java 的 Wrapped C++ 代码?

c++ - RapidXML 打印头有未定义的方法

c++类模板防止成员函数中的隐式转换

c# - 为什么 C# 泛型的设计行为与 C++ 模板如此不同?

c - 不兼容的指针类型传入 _Generic 宏

c++ - 段错误c++导致程序崩溃