我用模板写了类。类有 map 作为成员和一些 getxxx()/setxxx() 成员函数。
template<typename T1,typename T2>
class C1{
map<T1,T2> M;
public:
map<T1,T2> getM();
T2 getMvalue(T1 Key);
void setM(T1 key,T2 Value);
};
这里我想实现 getMvalue(),它接收键作为参数,如果“键”在 mapM 中可用,则返回相应的“值”。
它看起来像……
template<typename TKey,typename TValue>
T2 C1<T1,T2>::getMvalue(T1 Key){
if(M.count(Key)>0)
return M[Key];
else
return(???);
};
这里我需要用一些东西代替???。请记住,函数的返回类型是 T2,它可以是任何取决于用户决定的类型。 我怎样才能替换“???”用什么?
最佳答案
我鼓励您使用TryGet
模式
template<typename TKey,typename TValue>
bool C1<T1,T2>::tryGetMvalue(T1 key, T2& value){
if(M.count(key)>0) {
value = objProperties[key];
return true;
}
return false;
};
关于c++ - 我想在 C++ 中为 map<> 的给定 KEY 返回一个 VALUE。如果 KEY 不在 map<> 中,返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9622324/