I am a bit in stuck and need a help from C++ template guru. There is a template struct:
template<typename T, typename ID>
struct TypeMapping
{
T Type;
char* Name;
ID Id;
};
and a few template functions like this:
template<typename T, typename ID>
bool TryGetTypeByNameImp(const TypeMapping<T, ID> map[], size_t mapSize,
const char* name, T& type)
{
for (size_t i = 0; i < mapSize; i++)
{
if (strcmp(map[i].Name, name) == 0)
{
type = map[i].Type;
return true;
}
}
return false;
}
Map (the first parameter) is defined as (there are a few similar maps)
namespace audio
{
const TypeMapping<Type, AMF_CODEC_ID> Map[] =
{
{AAC, "aac", AMF_CODEC_AAC},
{MP3, "mp3", AMF_CODEC_MP3},
{PCM, "pcm", AMF_CODEC_PCM_MULAW}
};
const size_t MapSize = sizeof(Map)/sizeof(Map[0]);
}
Map is passed to a function as an argument and I am looking for how to pass it as template parameter so I can use functions like in this sample:
audio::Type type;
bool r = TryGetTypeByNameImp<audio::Map>("aac", type);
The only solution I found it is to define a struct which holds static Map and MapSize and use the struct as template parameter but I do not like this solution and I am looking for another one. Does anybody know how to do this?
This is trying to use
audio::Mapas a type – but it isn’t, it’s a variable. Just pass it to the function as a normal argument:That said, I have three remarks about your code:
x[]) does in reality declare it as a pointer. Your code uses this correctly, but using the array syntax is misleading. Use a pointer instead.char*is illegal in C++11, and deprecated in C++03 (since you are pointing to string literals). Usechar const*. Furthermore, I’d suggest using astd::stringargument in the function, and using the comparison operator==instead ofstrcmp.You are using an out-parameter,
type. I abhor this technique. If you want to return a value, use the return type. Since you also return a success value, use apairas the return type, unless there’s a very compelling reason not to:Ah, and I’d also consider using a
std::vectororstd::arrayhere instead of a C array. Then you don’t need to manually shlep the array size around through all the functions which use the array.