Reputation: 1
I am new to c++, I want to create different type of object by parameter, like this:
if (version_ == "v1") {
typename std::unordered_map<T, TIndex> uniq;
} else {
typename absl::flat_hash_map<T, TIndex> uniq;
}
uniq.reserve(2 * N);
However, this code compile failed:
error: 'uniq' was not declared in this scope
uniq.reserve(2 * N);
^
Then, I change the code:
std::unordered_map<T, TIndex> uniq1;
absl::flat_hash_map<T, TIndex> uniq2;
auto uniq = uniq1;
if (version_ == "v2") {
uniq = uniq2;
}
uniq.reserve(2 * N);
It also filed:
error: no match for 'operator=' (operand types are 'std::unordered_map<bool, long long int, std::hash<bool>, std::equal_to<bool>, std::allocator<std::pair<const bool, long long int> > >' and 'absl::flat_hash_map<bool, long long int, absl::hash_internal::Hash<bool>, std::equal_to<bool>, std::allocator<std::pair<const bool, long long int> > >')
uniq = uniq2;
^
How can I implement this feature in c++?
Upvotes: 0
Views: 47
Reputation: 66371
You can't determine a compile-time type at runtime.
What you can do is wrap all your work in templates, and then "kick off" with a specific type.
(That is, deploy the old "add a level of indirection" solution.)
Rough sketch:
template<typename Table>
void do_work(int N)
{
Table t;
t.reserve(2 * N);
....
}
//...
if (version == "v1")
{
do_work<std::unordered_map<T, TIndex>>(N);
}
else
{
do_work<absl::flat_hash_map<T, TIndex>>(N);
}
Upvotes: 1