我正在尝试创建一个奇怪的类,但是它的语法有问题。
#include <memory>
#include <iostream>
#include <string>
#include <typeinfo>
#include <map>
typedef std::shared_ptr<void> SharedVoidPointer;
typedef std::map <std::string, SharedVoidPointer > SharedPtrMap;
template<typename Ts = SharedPtrMap >
class CVar
{
public:
CVar() : mytype(typeid(Ts)) { //Create ourself as a Shared void pointer containing a Ts
Ts* var = new Ts();
ptr = SharedVoidPointer(var);
}
CVar(Ts& t) : mytype(typeid(Ts)) { //When we pass a type along to store, we now create ourself as a shared ptr of that type.
ptr = std::make_shared<Ts>(t);
}
template <typename T>
inline T& operator[] (const std::string& key) {
if (is<SharedPtrMap>()) { //We are a pointer map. Safe to continue
SharedPtrMap map = reinterpret_cast<SharedPtrMap>(ptr)[key]; //ptr is a map, so cast
SharedPtrMap::const_iterator it = map.find(key); //Check for existing key
if (it != map.end()) { //It already exists.
return NULL; //TODO: Compare types see if can be reassigned.
}
else{
return reinterpret_cast<T&>(map<T>[key]) ; //Probly not correct
}
}
else{
return NULL; //Pass error up.
}
}
template <typename T>
bool is(){
if (typeid(T) == mytype){
return true;
}
else{
return false;
}
}
private:
std::shared_ptr<void> ptr;
const std::type_info& mytype;
};
现在在我的示例程序中:
int main(){
CVar<> vars;
if (vars.is<std::string>())
std::cout << "Should not be string";
if (vars.is<SharedPtrMap>())
std::cout << "Should be map.";
std::string foo = "bar";
vars["foo"] = foo; //No operator [] matches arguments. Wha?
vars["foo"]<std::string&>(); Also a no go.
vars[]<std::string&>("foo"); //Even explicitly typing it does not work.
foo = "newbar";
std::cout << vars<std::string>["foo"]; //Should print newbar
return 0;
}
我对这堂课的期望如下:
vars["something"] = myvariablename;
vars["texture.bg"] = "mytexture.png";
vars["texture.fg"] = "mytexture2.png";
! Expectations:
vars["something"].is<std::string>() //true
vars["something"].is<std::int>() //false
vars["somthingelse"].is<std::string>() //false
vars["somthingelse"].exists() //false
vars["texture"].exists() //true
vars["texture"].is<SharedPtrMap> //true
vars["texture"] //Gives a Cvar<std::map<>>
vars["texture"]["bg"] //Gives std::string& ("mytexture.png")
vars["texture.bg"] //Gives std::string& ("mytexture.png")
我的问题似乎与下标运算符的重载有关。它真的不喜欢模板。我假设语法错误。
我也知道我没有“。”分离工作尚未实施。 Kinda挂在这台ATM上。
在 C++ Array Subscript Operator Template
调用操作员的唯一方法是显式编写list.operator []()。
对此进行了尝试,但即使这样也不起作用。