对于一些用于识别实例的跟踪自动化,我想调用以下任一方法:
- 包含对象的非静态方法返回其标识符
- 其他总是返回相同 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
};
我能否以某种方式避免使用诸如静态成员函数的特殊宏之类的变通方法(也许使用一些模板魔术)?