gpt4 book ai didi

c++ - 可变参数模板参数大小(不计算)

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

在 C++11 中,我可以通过这种方式获得参数的总大小:

template<typename First, typename... Rest>
size_t getSize( const First& first, const Rest& ...rest )
{
return getSize(first) + getSize( rest... );
}

template <typename T>
size_t getSize( const T& )
{
return sizeof(T);
}


std::cout << "Size of arguments is: " << getSize( short(0), double(0.0) ) << std::endl;

输出将是:“参数的大小是:10”。旧的 C++ 有什么类比吗?

附言也欢迎更好的 C++11 解决方案

最佳答案

对于 C++11,我会使用它,它由编译时求值。

#include <iostream>

template<typename First, typename... Rest>
struct total_size_of
{
static constexpr size_t value = total_size_of<First>::value + total_size_of<Rest...>::value;
};

template <typename T>
struct total_size_of<T>
{
static constexpr size_t value = sizeof(T);
};

int main() {
std::cout << "Size of arguments is: " << total_size_of<short, double>::value << std::endl;
return 0;
}

对于 C++11 之前的版本,我会使用这样的东西(由于缺少可变参数模板)。

#include <iostream>


template <typename T>
struct custom_size_of
{
static const size_t value = sizeof(T);
};

template <>
struct custom_size_of<void>
{
static const size_t value = 0;
};

template <typename One, typename Two = void, typename Three = void, typename Four = void>
struct total_size_of
{
static const size_t value = custom_size_of<One>::value + custom_size_of<Two>::value + custom_size_of<Three>::value + custom_size_of<Four>::value;
};


int main()
{
std::cout << "Size of arguments is: " << total_size_of<short, double>::value << std::endl;
return 0;
}

虽然 C++11 版本仍然很容易调整为一个自动确定参数类型的函数,但在 C++ 之前的版本中没有很好的解决方案。

C++11:

template <typename...Args>
size_t get_size_of(Args...args)
{
return total_size_of<Args...>::value;
}

C++11 之前的版本:

template <typename One>
static size_t get_size_of(const One&)
{
return total_size_of<One>::value;
}
template <typename One, typename Two>
static size_t get_size_of(const One&, const Two&)
{
return total_size_of<One, Two>::value;
}
template <typename One, typename Two, typename Three>
static size_t get_size_of(const One&, const Two&, const Three&)
{
return total_size_of<One, Two, Three>::value;
}
template <typename One, typename Two, typename Three, typename Four>
static size_t get_size_of(const One&, const Two&, const Three&, const Four&)
{
return total_size_of<One, Two, Three, Four>::value;
}

关于c++ - 可变参数模板参数大小(不计算),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429583/

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