在c++中通过参数创建不同类型的对象?

问题描述 投票:0回答:1

我是C++新手,我想通过参数创建不同类型的对象,就像这样。

if (version_ == "v1") {
    typename std::unordered_map<T, TIndex> uniq;
} else {
    typename absl::flat_hash_map<T, TIndex> uniq;
}

uniq.reserve(2 * N);

但是,这段代码编译失败。

 error: 'uniq' was not declared in this scope
       uniq.reserve(2 * N);
       ^

然后,我修改了代码

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);

它也归档了。

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;
                ^

我如何在c++中实现这个功能?

c++ c++11
1个回答
1
投票

你不能在运行时确定一个编译时类型。

你可以做的是把你所有的工作都包在模板中,然后用一个特定的类型 "踢开"。(也就是说,部署老的 "增加一层间接性 "的解决方案)。

粗略的草图。

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.