gpt4 book ai didi

c++ - 帮助更正源代码,使用模板

转载 作者:行者123 更新时间:2023-11-30 03:12:45 32 4
gpt4 key购买 nike

我尝试编译发布的示例(C++ Service Providers),但未能通过 VS8 VC9。我对模板的经验很少。
有什么建议吗?
坦克。

这些是错误:
dictionarySTL.cpp(40) : error C2663: 'std::_Tree<_Traits>::find' : 2 重载没有 'this' 指针的合法转换
dictionarySTL.cpp(48) : error C2679: binary '[' : no operator found which takes a right-hand operand of type 'const type_info *__w64 ' (or there are no acceptable conversion)

#include <typeinfo>
#include <map>
#include <string>
using namespace std;

class SomeClass
{
public:
virtual ~SomeClass() {} // virtual function to get a v-table
};

struct type_info_less
{
bool operator() (const std::type_info* lhs, const std::type_info* rhs) const
{
return lhs->before(*rhs) != 0;
}
};

class TypeMap
{
typedef map <type_info *, void *, type_info_less> TypenameToObject;
TypenameToObject ObjectMap;

public:
template <typename T>
T *Get () const
{
TypenameToObject::const_iterator iType = ObjectMap.find(&typeid(T));
if (iType == ObjectMap.end())
return NULL;
return reinterpret_cast<T *>(iType->second);
}
template <typename T>
void Set(T *value)
{
ObjectMap[&typeid(T)] = reinterpret_cast<void *>(value);
}
};

int main()
{
TypeMap Services;
Services.Set<SomeClass>(new SomeClass());
SomeClass *x = Services.Get<SomeClass>();
}

最佳答案

要编译此代码,请执行以下行:

typedef map<type_info *, void *, type_info_less> TypenameToObject;

应该是:

typedef map<const type_info *, void *, type_info_less> TypenameToObject;

关于c++ - 帮助更正源代码,使用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/417788/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com