gpt4 book ai didi

c++ - 在 std::conditional 中使用不完整类型的 sizeof

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:53 24 4
gpt4 key购买 nike

这是一个最小的例子:

struct incomplete_type;

template<typename T>
struct foo
{
using type = std::conditional_t<std::is_arithmetic_v<T>,
std::conditional_t<sizeof(T) < sizeof(void*), int, float>,
double>;
};

foo<incomplete_type> f;会导致错误,因为它会对类型执行 sizeof,即使 incomplete_type不是算术类型(iow,它不会在逻辑上进入 sizeof 分支)。 live demo

所以,我想推迟 sizeof :

第一次尝试(失败)

template<typename T>
auto
foo_aux()
{
if(sizeof(T) < sizeof(T*))
return 0;
else
return 0.0f;
}

conditional_t<std::is_arithmetic_v<T>, decltype(foo_aux<T>()), double>仍然触发相同的错误。

第二次尝试(失败)

template<typename T, bool>
struct foo_aux_aux
{
using type = float;
};
template<typename T>
struct foo_aux_aux<T, true>
{
using type = int;
};

template<typename T, bool = false>
struct foo_aux : foo_aux_aux<T, sizeof(T) < sizeof(void*)>
{};

conditional_t<std::is_arithmetic_v<T>, typename foo_aux<T>::type, double>仍然触发相同的错误。

第三次尝试(成功)

template<typename T, bool comp>
struct foo_aux_aux
{
using type = float;
};
template<typename T>
struct foo_aux_aux<T, true>
{
using type = int;
};

template<typename T, bool isArithmeticType>
struct foo_aux
{
using type = double;
};

template<typename T>
struct foo_aux<T, true>
{
using type = typename foo_aux_aux<T, sizeof(T) < sizeof(void*)>::type;
};

Yes, it works as expected ,但它真的很乏味和丑陋。

你有什么优雅的方法吗?

最佳答案

在 C++17 中,您可以使用 if constexpr 进行类型计算。只需将类型包装到虚拟容器中并使用值计算,然后通过 decltype 检索类型。

struct foo 可以这样实现:

template<class T>
struct type_ {
using type = T;
};

template<class T>
struct foo {
auto constexpr static type_impl() {
if constexpr (std::is_arithmetic<T>{}) {
if constexpr (sizeof(T) < sizeof(void*)) {
return type_<int>{};
} else {
return type_<float>{};
}
} else {
return type_<double>{};
}
}

using type = typename decltype(type_impl())::type;
};

static_assert(std::is_same<foo<incomplete_type>::type, double>{});

关于c++ - 在 std::conditional 中使用不完整类型的 sizeof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53569311/

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