在C++中是否有可能拥有一个static和virtual?的成员函数?显然,没有一种直接的方法(static virtual member();编译错误),但是至少有一种方法可以达到同样的效果吗?
IE:
struct Object
{
struct TypeInformation;
static virtual const TypeInformation &GetTypeInformation() const;
};
struct SomeObject : public Object
{
static virtual const TypeInformation &GetTypeInformation() const;
};
Run Code Online (Sandbox Code Playgroud)
这是有道理的使用GetTypeInformation()上的一个实例(都object->GetTypeInformation())和一类(SomeObject::GetTypeInformation()),它可以为模板,比较有用和重要.
我能想到的唯一方法包括编写两个函数/一个函数和一个常量,每个类,或使用宏.
还有其他方法吗?
我正在创建这样的函数:
void SetItem(const Key &key, const Value &value)
{
...
}
Run Code Online (Sandbox Code Playgroud)
键和值是某种类型.
在内部,我想像这样存储这对:
std::pair<const Key &, Value>
Run Code Online (Sandbox Code Playgroud)
所以这是我的问题:我需要强制Key实际上是一个l值,以便在函数退出时不会被清除(带有r值的不安全)
我可以为函数签名:
void SetItem(Key &key, const Value &value)
Run Code Online (Sandbox Code Playgroud)
这将阻止使用r值,但它不允许使用const键,我也不喜欢.
有没有办法让我在保留常量的同时强制Key成为l值?
我可以创建一个r值重载来防止它:
void SetItem(Key &&key, const Value &value)
{
[What do I put here?]
}
Run Code Online (Sandbox Code Playgroud)
谢谢