懒惰的评价

时间:2011-03-15 19:13:12

标签: c++ metaprogramming lazy-evaluation

我如何懒惰评估std :: conditional中的第二个arg?

#include "stdafx.h"
#include <type_traits>

struct Null{};
struct _1{enum {one = true,two = false};};
struct _2{enum {two = true, one = false};};

template<class T>
struct is_nulltype
{
    enum {value = false};
};

template<>
struct is_nulltype<Null>
{
    enum {value = true};
};

template<class T>
struct X : std::conditional<is_nulltype<T>::value,Null,typename std::conditional<T::one,_1,_2>::type>::type
{
};

int _tmain(int argc, _TCHAR* argv[])
{
X<Null> x;//won't compile no Null::one but I don't need that member in Null at all
    return 0;
}

1 个答案:

答案 0 :(得分:9)

通常的技巧是让std::conditional在两个元函数之间进行选择:

template <typename T>
struct false_case {
  typedef typename std::conditional<T::one,_1,_2>::type type;
};

struct always_null {typedef Null type;};

template<class T>
struct X :
  std::conditional<is_nulltype<T>::value,
                   always_null,
                   false_case<T>
                  >::type::type { ... };

请注意::type之后的两个std::conditional