gpt4 book ai didi

c++ - 在 lambda 表达式和模板 typedef 习语中提取对成员

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:36:57 31 4
gpt4 key购买 nike

我这里有一些复杂的类型,所以我决定使用巧妙的技巧在模板化类型上使用 typedef。然后我有一个类 some_container 有一个容器作为成员。容器是由元素和 vector 组成的对 vector 。我想用 lambda 表达式编写 std::find_if 算法来查找具有特定值的元素。要获取值,我必须先调用 pair,然后从元素中获取值。在我的 std::find_if 下面有一个正常的循环可以解决问题。我的 lambda 无法编译。如何访问对内元素内的值?我使用 g++ 4.4+ 和 VS 2010,现在我想坚持使用 boost lambda。

#include <vector>
#include <algorithm>
#include <boost\lambda\lambda.hpp>
#include <boost\lambda\bind.hpp>

template<typename T>
class element
{
public:
T value;
};

template<typename T>
class element_vector_pair // idiom to have templated typedef
{
public:
typedef std::pair<element<T>, std::vector<T> > type;
};

template<typename T>
class vector_containter // idiom to have templated typedef
{
public:
typedef std::vector<typename element_vector_pair<T>::type > type;
};

template<typename T>
bool operator==(const typename element_vector_pair<T>::type & lhs, const typename element_vector_pair<T>::type & rhs)
{
return lhs.first.value == rhs.first.value;
}

template<typename T>
class some_container
{
public:
element<T> get_element(const T& value) const
{
std::find_if(container.begin(), container.end(), bind(&typename vector_containter<T>::type::value_type::first::value, boost::lambda::_1) == value);
/*for(size_t i = 0; i < container.size(); ++i)
{
if(container.at(i).first.value == value)
{
return container.at(i);
}
}*/
return element<T>(); //whatever
}

protected:
typename vector_containter<T>::type container;
};

int main()
{
some_container<int> s;
s.get_element(5);
return 0;
}

最佳答案

两个问题。

你要追求的东西(element<T>::value)不是类型名。

但是,首先您需要嵌套绑定(bind):一个用于访问 _1.first另一个访问 value以前的。

没有类型定义:

  std::find_if(
container.begin(), container.end(),
bind(
&element<T>::value,
bind(&std::pair<element<T>, std::vector<T> >::first, boost::lambda::_1)
) == value
);

因此,使用您的成语,没有不必要的 typename:

  std::find_if( container.begin(), container.end(),
bind(
&vector_containter<T>::type::value_type::first_type::value,
bind(
&vector_containter<T>::type::value_type::first, boost::lambda::_1)
) == value
);

不过,这似乎不是特别可读。也许 a) 等待 C++0x lambda,b) 为 find_if 编写一个特定的仿函数调用,c) 只做一个手动循环。

关于c++ - 在 lambda 表达式和模板 typedef 习语中提取对成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2496471/

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