S
shaun
I'm doing some work with const maps of various types and I find that I'm
writing the same few lines of code over and over:
(having declared and initialized a map<myTypeA, myTypeB> myMap)
myTypeB errvalue(anErrorValue);
map<myTypeA, myTypeB>::const_iterator ppair(myMap.find(theKey));
myTypeB foundValue = (ppair not_eq myMap.end())?ppair->second:errValue;
I'd like to template this as :
template <class S, class T>
T constFind(const map< S, T > & theMap, const S & theKey, const T &
errVal){
map< S, T>::const_iterator ppair(theMap.find(theKey));
return (ppair not_eq theMap.end())?(ppair->second):errVal;
}
and then in the body of the code just have
theValue = constFind(myMap, aKey, anErrVal);
on one of my compilers (gcc 3.2.3) this appears to compile (havent tried
running it), on the other (gcc 4.0.0) it doesn't. (I can't guarantee
that all compiler options are the same)
If I change the type of ppair to be pair< S, T> *, the situation is
reversed; either way, I don't trust that the code will work as I think
it should and for the moment I am overloading a 'constFind' function for
the specific maps I am using.
Is it possible to write a more generic templated version?
cheers
shaun
writing the same few lines of code over and over:
(having declared and initialized a map<myTypeA, myTypeB> myMap)
myTypeB errvalue(anErrorValue);
map<myTypeA, myTypeB>::const_iterator ppair(myMap.find(theKey));
myTypeB foundValue = (ppair not_eq myMap.end())?ppair->second:errValue;
I'd like to template this as :
template <class S, class T>
T constFind(const map< S, T > & theMap, const S & theKey, const T &
errVal){
map< S, T>::const_iterator ppair(theMap.find(theKey));
return (ppair not_eq theMap.end())?(ppair->second):errVal;
}
and then in the body of the code just have
theValue = constFind(myMap, aKey, anErrVal);
on one of my compilers (gcc 3.2.3) this appears to compile (havent tried
running it), on the other (gcc 4.0.0) it doesn't. (I can't guarantee
that all compiler options are the same)
If I change the type of ppair to be pair< S, T> *, the situation is
reversed; either way, I don't trust that the code will work as I think
it should and for the moment I am overloading a 'constFind' function for
the specific maps I am using.
Is it possible to write a more generic templated version?
cheers
shaun