c++ - 在 C++ 中是否存在 std::conditional 的惰性等效项?

标签 c++ stl c++17 template-meta-programming sfinae

来电后 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/

相关文章:

c++ - std::vector 如何调整其内部缓冲区的大小?

c++ - 在 Boost zip 迭代器上使用 C++17 并行执行算法时,为什么会出现 MSVC 错误?

C++ 模板 - 完整指南 : Wording of footnote about decltype and return type

c++ - 当我到达 z 方向的某个位置时,我的 "camera"被反转,这可能是什么原因造成的?

c++,我可以使用 enable_if 而不是复制粘贴来启用多个特征类特化吗?

c++ - 从指向的对象中重新分配 shared_ptr

C++ std::bind 到 std::function,在 VS2015 中出了什么问题?

c++ - 使用后递增索引的数组分配中的异常安全

c++ - 模板参数列表中的部分模板推导

c++ - 模板类型推导失败(std::empty 作为谓词)