Let's say we have the following structure defined
template <char T, char S>
struct chars_trait {}
Moreover, we have a bunch of two-char strings, for instance
const std::string ab = "ab";
const std::string cd = "cd";
const std::string ef = "ef";
My goal is to create chars_trait object for each of those strings, so
ab -> chars_trait<'a','b'>{}
cd -> chars_trait<'c','d'>{}
ef -> chars_trait<'e','f'>{}
and use them, for instance, like this
std::for_each(vecOfStrs.begin(), vecOfStrs.end(),
[&](const std::string& str){doSthWithCharsTrait(getCharTrait(str));});
I have tried to employ a map but got stuck with two problems - first that this approach is possible from c++14, and second, much more significant - it does not work. So my question is - can I somehow improve my code? Or there is no chance of making it as I proposed?
All code here
#include <iostream>
#include <string>
#include <map>
const std::string ab = "ab";
const std::string cd = "cd";
const std::string ef = "ef";
template <char T, char S>
struct chars_trait {};
template <char T, char S>
std::map<std::string, chars_trait<T, S>> MAPPER
{
{ab, chars_trait<'a', 'b'>{}},
{cd, chars_trait<'c', 'd'>{}},
{ef, chars_trait<'e', 'f'>{}}
};
template <char T, char S>
void print(const chars_trait<T, S>&)
{
std::cout << T << S << std::endl;
}
void print(const std::string& str)
{
print(MAPPER.at(str));
}
int main()
{
print(ab);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire