Lazy evaluation
Asked Answered
L

1

10

How can I lazy evaluate second arg in std::conditional?

#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;
}
Largely answered 15/3, 2011 at 19:13 Comment(3)
For the problem at hand, just specialize X for type Null.Osteoblast
@Alf it would mean that I have to have two "almost" identicall classes. No go.Largely
It looks like what you're looking for here is "lazy compilation" and not "lazy evaluation". The substitution of Null for T in the definition of X causes a syntax error. The evaluation of the syntax cannot be delayed.Offer
G
9

The usual technique for this is to have the std::conditional choose between two metafunctions:

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 { ... };

Note the two ::types after std::conditional now.

Grisette answered 15/3, 2011 at 20:29 Comment(2)
false_case can have the conditional as base class to make it a bit shorter.Psychometry
thanks, I think it will do what I've intened to. If not I'll let you know.Largely

© 2022 - 2024 — McMap. All rights reserved.