1

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

  • 包含对象的非静态方法返回其标识符
  • 其他总是返回相同 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
};

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

4

3 回答 3

1

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

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;
}
于 2009-09-17T17:50:17.383 回答
0

您是否需要像示例中那样为每个类的每个实例使用不同的标识符,或者您只是想确定跟踪中的类?

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

于 2009-09-17T17:34:44.793 回答
0

您也许可以使用Boost TypeTraits 库中的is_member_function_pointer。sbi 关于在静态和非静态情况下使用不同代码的建议可能会更好。

于 2009-09-17T17:45:00.610 回答