gpt4 book ai didi

c++ - 如何在不实例化类型的情况下确定两种 C++ 类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:30 25 4
gpt4 key购买 nike

我有以下问题:

我想在不实际评估“结果”类型的情况下确定两种类型 - 因为该类型可能根本不存在 - 是无效的。 (请不要使用 C++11 的东西)

例子:

 #include <iostream>
#include <iterator>

template <bool B, typename T, typename F>
struct TemplateIf {
};

template <typename T, typename F>
struct TemplateIf<true, T, F> {
typedef T Result;
};

template <typename T, typename F>
struct TemplateIf<false, T, F> {
typedef F Result;
};


int main(int argc, char** argv)
{

// On GCC this is error as std::iterator_traits<int>::value_type doesn't exist
typename TemplateIf<true, int, std::iterator_traits<int>::value_type >::Result a;
a = 5;

std::cout << a << std::endl;

return 0;
}

它能以某种方式确定吗? (假设选择的类型始终有效,但未选择的类型可能无效)。

最佳答案

不是直接传递类型,而是传递一个计算类型的元函数。然后可以在 if 中延迟评估此元函数。

#include <iostream>
#include <iterator>

template <bool B, typename T, typename F>
struct TemplateIf {};

template <typename T, typename F>
struct TemplateIf<true, T, F> {
typedef typename T::type Result;
};

template <typename T, typename F>
struct TemplateIf<false, T, F> {
typedef typename F::type Result;
};

template <typename T>
struct get_value_type {
typedef typename std::iterator_traits<T>::value_type type;
};

template <typename T>
struct identity {
typedef T type;
};

int main(int argc, char** argv)
{
TemplateIf<true, identity<int>, get_value_type<int> >::Result a;
a = 5;
std::cout << a << std::endl;
return 0;
}

关于c++ - 如何在不实例化类型的情况下确定两种 C++ 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12035026/

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