在模板方法中确定STL容器中项目的数据类型
我正在尝试编写一个模板方法来处理STL容器中的项目。获取容器的详细信息很容易(我使用std :: enable_if子句允许该模板方法仅在容器迭代时才能调用(检测一个begin()方法。))我需要进一步了解数据容器持有的类型。这是有效的方法:
template <typename CONTAINER>
std::string doStuff(const CONTAINER & container) {
using CONTAINER_TYPE = typename CONTAINER::value_type;
}
如果在此方法中constexpr ,我可以使用来执行某些事情,如果我还可以确定容器中持有的内容的类型。这里的代码无法正常工作,但就像我要尝试的那样:
template <typename CONTAINER, typename ITEM>
std::string doStuff(const CONTAINER<ITEM> & container) {
using CONTAINER_TYPE = typename CONTAINER::value_type;
using ITEM_TYPE = typename ITEM::value_type;
}
完全有道理,为什么我不能以这种方式调用该方法,但是我该怎么办(在调用该方法或在方法中使用元编程)确定容器中项目的类型。我想这样做,以使其在编译时已知。
(我已经尝试了几个DECTTYPE和INDOKE_RESULT和大量搜索的排列,但尚无目的。
using ITEM_TYPE = std::invoke_result<&CONTAINER::begin>::type;
)似乎在这里正常工作。
I'm trying to write a template method to handle items in an STL container. Getting details of the container is easy (and I use a std::enable_if clause to allow this template method to be called only if the container can be iterated over (detects a begin() method.)) I further need to know the data type held by the container. Here's what works:
template <typename CONTAINER>
std::string doStuff(const CONTAINER & container) {
using CONTAINER_TYPE = typename CONTAINER::value_type;
}
I can use if constexpr
within this method to do certain things if I can also determine the type of the things held in the container. Here's code that won't work but is like what I'm trying for:
template <typename CONTAINER, typename ITEM>
std::string doStuff(const CONTAINER<ITEM> & container) {
using CONTAINER_TYPE = typename CONTAINER::value_type;
using ITEM_TYPE = typename ITEM::value_type;
}
It completely makes sense why I can't invoke the method this way, but what could I do (either in invoking the method or with metaprogramming inside the method) to determine the type of the items in the container. I'd like to do it such that it is known at compile time.
(I've tried a couple permutations of decltype and invoke_result and tons of searching but nothing is quite working yet.) I've tried for example:
using ITEM_TYPE = std::invoke_result<&CONTAINER::begin>::type;
Of course, that returns an iterator type which needs to be dereferenced but '*' doesn't seem to work as expected here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用模板模板参数:
You could use template template parameters:
您可以使用一些Sfinae添加额外的
typename
(我将使用C ++ 20方法)
You might simply add extra
typename
Possibly with some SFINAE (I will use C++20 way)