对于一些用于识别实例的跟踪自动化,我想调用:
- 返回其标识符的包含对象的非静态方法
- 总是返回相同 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/