本文介绍了递归解压缩模板包以实现无参数功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试使用可变参数模板类型包创建一个结构模板,该模板可以扣除传入的所有类型的大小之和.

I'm trying to create a struct template with a variadic template type pack, that can deduct the sum of the size of all types passed in.

在下面找到一个简化的示例,在实际环境中,计算出的大小用于创建其他成员对象.

Below you find a simplified example, in the real-world context, the size computed is used to create further member objects.

template <typename... Types>
struct OverallSize
{
    template <typename FirstType, typename... NextTypes>
    static constexpr size_t sizesum() { return sizeof (FirstType) + sizesum<NextTypes...>(); }
    template <typename LastType>
    static constexpr size_t sizesum() { return sizeof (LastType); }

    static constexpr size_t size = sizesum<Types...>();
};

// Should work e.g. like this
auto s = OverallSize<int, float, char>::size; // s will be 9 on x86-64

在涉及参数列表时,我习惯于这种递归参数解压缩方法,并假定此方法在无参数函数和显式模板规范中也能正常使用.但是在用clang编译时出现以下错误

I'm used to this recursive parameter unpacking approach when it comes to argument lists and assumed this works as well with argument-less functions and explicit template specification. However I get the following error when compiling with clang

Call to 'sizesum' is ambiguous
...
Candidate function [with FirstType = unsigned long, NextTypes = <>]
Candidate function [with LastType = unsigned long]

因此,似乎最后一个递归迭代在这里不起作用–不知道为什么编译器不会简单地选择最明显的选择:只有一个模板类型的选择–就像如果有一个传递给函数的实际模板参数.

So it seems as if the last recursion iteration doesn't work here – not sure why the compiler doesn't simply chose the most obvious choice: The one with only one template type – just as it would happen if there was an actual template argument passed to the function.

那么,我该怎么做才能使它按要求进行编译和工作?

So, what do I have to do to make this compile and work as desired?

推荐答案

对于C ++ 14,您可以使用SFINAE:

For C++14 you can use SFINAE:

template <
    typename FirstType,
    typename... NextTypes,
    std::enable_if_t<sizeof...(NextTypes) >= 1>* = nullptr >
static constexpr size_t sizesum() {
    return sizeof (FirstType) + sizesum<NextTypes...>();
}

仅当参数包的大小大于等于1时,才会考虑使用此模板.

this template will be considered only if parameters pack has size >= 1.

演示

这篇关于递归解压缩模板包以实现无参数功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:42