【发布时间】:2014-07-08 01:48:54
【问题描述】:
首先是我的用例,因为我可能认为方向错误:我想创建一个将值映射到类型的映射。比如:
Map<std::string> map;
map.insert<int, double, char>("Hey");
auto string = map.at<int, double, char>();
使用std::type_index 就很容易做到这一点。但是,当它们可转换时,我想添加匹配与搜索的类型不完全相同的类型的可能性。所以下面也应该返回"Hey",因为float可以转换成double:
auto string = map.at<int, float, char>();
我不能在这种情况下使用type_index,因为std::is_convertible 只能直接用于类型。 This would be the version without conversion,但就其而言,在不进行重大更改的情况下添加转换处理似乎并不容易。
我当前的尝试类似于以下内容,请注意这不起作用,只是显示了我尝试实现的内容:
template<typename T>
class Map {
T value;
std::vector<Map<T>> children; // all the children of the current node.
// in the above example, if this was
// the int node, the only child
// would be the double node
template<typename T1>
constexpr bool is_convertible() const {
return std::is_convertible<__T__, T1>::value; // this isn't applicable
// since __T__ can't be
// stored (this nodes
// type)
}
public:
template<typename T1, typename... Tn>
void insert(T&& value) {
// iterate through/create the child nodes until the last template param
}
template<typename T1, typename... Tn>
T& at() {
// iterate through thechild nodes until a matching child is found
// either exact match or a convertible
for(auto &c: children) {
// if the above function would work
if(c.template is_convertible<T1>()) {
return c.template at<Tn...>();
}
}
}
}
现在我不知道如何实现这一目标。我想将 lambdas 实现为比较器函数,但是虽然 lambda 可以存储当前节点的类型,但它不能在调用时接受模板参数进行比较。
是否有一些 C+1y 通用 lambda 比较器魔法,甚至更简单的方法?
【问题讨论】:
-
键值对是在运行时创建还是仅在编译时创建?你到底想用这个来完成什么?
-
如果我理解正确,那么这个想法取决于虚拟模板函数,在这种情况下实际上是不可用的。
-
@Svalorzen 在编译时。
-
虽然我对
c.template get<Tn...>(value)行完全感到困惑,但这与我的理解相矛盾。这个问题毫无意义。 -
你不能只创建一个模板结构映射,它接受可变数量的模板参数,然后预先专门化你可能想要的任何组合吗?我必须坚持,如果你想用这个来解决一些真正的问题,你可能会走错路。
标签: c++ c++11 types lambda c++14