考慮在std::any_of
應如何將二元謂詞傳遞給用戶定義的Boost.MPL算法?
#include <iostream> // cout
#include <type_traits> // is_base_of, is_pod
#include <boost/mpl/apply.hpp> // apply
#include <boost/mpl/fold.hpp> // fold
#include <boost/mpl/lambda.hpp> // lambda, _1, _2
#include <boost/mpl/logical.hpp> // and_, true_
#include <boost/mpl/vector.hpp> // vector
template
<
typename Sequence,
typename Pred
>
struct all_of
:
boost::mpl::fold<
Sequence,
boost::mpl::true_,
boost::mpl::lambda<
boost::mpl::and_<
boost::mpl::_1,
boost::mpl::apply< Pred, boost::mpl::_2 >
>
>
>
{};
typedef int P1; typedef char P2; typedef float P3;
typedef boost::mpl::vector<
P1, P2, P3
> pod_types;
struct B {}; struct D1: B {}; struct D2: B {}; struct D3: B {};
typedef boost::mpl::vector<
D1, D2, D3
> derived_types;
int main()
{
std::cout << (std::is_pod<P1>::value) << '\n'; // true
std::cout << (std::is_pod<P2>::value) << '\n'; // true
std::cout << (std::is_pod<P3>::value) << '\n'; // true
std::cout << (
all_of<
pod_types,
std::is_pod<boost::mpl::_1>
>::type::value // true
) << '\n';
std::cout << (std::is_base_of<B, D1>::value) << '\n'; // true
std::cout << (std::is_base_of<B, D2>::value) << '\n'; // true
std::cout << (std::is_base_of<B, D3>::value) << '\n'; // true
std::cout << (
all_of<
derived_types,
std::is_base_of< B, boost::mpl::_1 >
>::type::value // false (but should be true)
) << '\n';
return 0;
}
一個Boost.MPL風格的元編程版本以下嘗試這種打印出:1 1 1 1 1 1 1 0。即,all_of
最後調用與std::is_base_of
作謂語通過生成假。爲什麼這不起作用?顯然,基類B
沒有得到正確的綁定到謂詞。我應該如何傳遞一個二元謂詞? mpl :: lambda或mpl :: bind的組合?
UPDATE
基於呂克Touraille的出色答卷,這裏是免費的λ-解決我的問題,以作爲一個額外的獎金none_of
編譯時的版本和any_of
template<typename Sequence, typename Pred>
struct all_of
:
std::is_same< typename
boost::mpl::find_if<
Sequence,
boost::mpl::not_<Pred>
>::type, typename
boost::mpl::end<Sequence>::type
>
{};
template<typename Sequence, typename Pred>
struct none_of
:
all_of< Sequence, boost::mpl::not_<Pred> >
{};
template<typename Sequence, typename Pred>
struct any_of
:
boost::mpl::not_< none_of< Sequence, Pred > >
{};
它不會在第一種情況下工作之一:如果您在'pod_types'添加非莢,你會看到'all_of'仍然返回true 。 –
2012-02-22 08:24:06
@Luc Touraille一個永遠不能測試的足夠!我也應該測試一個消極的結果。有趣的是,一元謂詞映射爲真,二元謂詞映射爲假。 – TemplateRex 2012-02-22 10:32:09