gpt4 book ai didi

c++ - Boost/C++ eval_if 失败

转载 作者:行者123 更新时间:2023-11-28 06:13:55 24 4
gpt4 key购买 nike

以下程序说明了一个问题,我遇到了一个非常困难的时期:它看起来像第 51 行中的 eval_if 没有正常工作。也就是说,当两种类型都不是安全类型时,将调用 metafuction get_promotion_policy。我已经为此工作了两天,看不到发生了什么。来自 TMP genious 的任何帮助将不胜感激。

#include <type_traits>
#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>

struct safe_tag {};

template<class T, class P = void>
struct safe : public safe_tag {
T m_t;
typedef P PromotionPolicy;
};

template<class T>
struct is_safe : public
//std::is_arithmetic<T>
std::is_base_of<safe_tag, T>
{};

template<class T, class U>
struct common_policies {
static_assert(
boost::mpl::or_<
is_safe<T>,
is_safe<U>
>::value,
"at least one type must be a safe type"
);

template<typename Z>
struct get_promotion_policy {
static_assert(
is_safe<Z>::value,
"only safe types have promotion policies"
);
typedef typename Z::PromotionPolicy type;
};


// if both types are safe, the policies have to be the same!
static_assert(
boost::mpl::eval_if<
boost::mpl::and_<
is_safe<T>,
is_safe<U>
>,
typename std::is_same<
typename get_promotion_policy<T>::type,
typename get_promotion_policy<U>::type
>::type,
boost::mpl::identity<boost::mpl::true_>
>::type::value,
"if both types are safe, the policies have to be the same!"
);

// now we've verified that there is no conflict between policies
// return the one from the first safe type
typedef typename boost::mpl::if_<
is_safe<T>,
T,
typename boost::mpl::if_<
is_safe<U>,
U,
//
boost::mpl::void_
>::type
>::type safe_type;

typedef typename get_promotion_policy<safe_type>::type promotion_policy;

};

common_policies<int, safe<int> > t;

int main(){
return 0;
}

最佳答案

typename std::is_same<
typename get_promotion_policy<T>::type,
typename get_promotion_policy<U>::type
>::type

触发 get_promotion_policy<T> 的实例化和 get_promotion_policy<U> ,即使它在错误的分支中。您必须报告评估,例如:

// if both types are safe, the policies have to be the same!
static_assert(
boost::mpl::eval_if<
boost::mpl::and_<
is_safe<T>,
is_safe<U>
>,
std::is_same<
typename boost::mpl::eval_if<is_safe<T>, get_promotion_policy<T>, boost::mpl::identity<void>>::type,
typename boost::mpl::eval_if<is_safe<U>, get_promotion_policy<U>, boost::mpl::identity<void>>::type
>,
boost::mpl::identity<boost::mpl::true_>
>::type::value,
"if both types are safe, the policies have to be the same!"
);

Demo

关于c++ - Boost/C++ eval_if 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30689117/

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