来电后 std::contional<bool, T1, T2>
无论 bool 的值如何,类型 T1 和 T2 都会在调用后立即实例化,是否存在仅实例化相关类型的实现(或一些实现它的指针)。
例如,以下代码是不可能使用 std::conditional 编写的。我们甚至不能在结构上使用 SFINAE(在示例中)。
struct Term {};
template <int N, typename T, typename ...Ts>
struct PairList
{
static constexpr int i = N;
using type = T;
using tail = PairList<N + 1, Ts...>;
};
template <int N, typename T>
struct PairList<N, T>
{
static constexpr int i = N;
using type = T;
using tail = Term;
};
template <int N, typename pairList>
struct get
{
static constexpr auto good = (N == pairList::i);
using T = typename std::conditional<
good,
typename pairList::type,
typename get<N, typename pairList::tail>::T>::type; // The second parameter might not be defined
};
最佳答案
您可以使用 if constexpr
在保持熟悉的代码结构的同时延迟实例化模板:
// C++20: std::type_identity
template<typename T>
struct type_t {
using type = T;
};
template <int N, typename pairList>
struct get
{
static auto choose_type() {
if constexpr (N == pairList::i) {
return type_t<typename pairList::type>{};
} else {
return type_t<typename get<N, typename pairList::tail>::T>{};
}
}
using T = typename decltype(choose_type())::type;
};
关于c++ - 在 C++ 中是否存在 std::conditional 的惰性等效项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62746757/