gpt4 book ai didi

c++ - 按类型获取元组元素(C++0x 之前)

转载 作者:太空宇宙 更新时间:2023-11-04 11:49:49 25 4
gpt4 key购买 nike

我有一个包含元组的模板化类,并希望能够在编译时按类型检索元素。为了简化事情,容器类被限制为最多三个条目:

template< class U = null_type, class V = null_type, class W = null_type >
class TupleContainer {
public:

template< class ReturnT >
ReturnT& getElementbyType() {
return get< ReturnT >(data_);
}

private:
boost::tuple< U, V, W > data_;
}

阅读 Get index of a tuple element's type 的答案和 For std::tuple, how to get data by type, and how to get type by index?我通过递归访问者方法实现了这一点,并且使用具有 c++11 功能的 GNU C++ 编译器工作得很好。

template< int Index, class Search, class First, class... Types >
struct get_internal
{
typedef typename get_internal< Index + 1, Search, Types...>::type type;
static constexpr int index = Index;
};

template< int Index, class Search, class... Types >
struct get_internal< Index, Search, Search, Types... >
{
typedef get_internal type;
static constexpr int index = Index;
};

template< class T, class... Types >
T& get( std::tuple< Types... >& tuple )
{
return std::get< get_internal< 0, T, Types... >::type::index >(tuple);
}

我现在必须将我的代码移植到 Windows。由于某些外部库的限制,我必须使用 Visual Studio 2010,它似乎不支持可变参数模板。

我确信有一个解决方法(因为 boost::tuple 也可以在不支持可变参数模板的情况下使用)但是我对整个模板元编程主题仍然很陌生,还没有找到解决方案。

那么有没有人知道在 Visual Studio 2010 中不使用可变参数模板的情况下解决这个问题的方法?

顺便说一句:访问者方法即使对于元素远远超过三个的元组也能很好地工作。容器将被限制为 3 或 4 个元组元素,因此我什至不介意将索引硬编码到我的实现中。

最佳答案

您不需要预处理器来生成大量重载,只需调整您的 get_internal 方法即可在没有可变参数模板的情况下工作。它们需要有类似数量的参数,例如 TupleContainer:

template< class R, class U, class V, class W >
struct getIndex
{
static const int value = getIndex< R, V, W, null_type >::value + 1;
};

template< class R, class V, class W >
struct getIndex< R, R, V, W >
{
static const int value = 0;
};

template< class R >
struct getIndex< R, null_type, null_type, null_type >
{
// let it fail if the type is not found and avoid infinite recursion
};

现在你可以使用

template< class R >
R& getElementByType() {
return get< getIndex< R, U, V, W >::value >(data_);
}

关于c++ - 按类型获取元组元素(C++0x 之前),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18812630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com