特定类型的可变模板 [英] variadic template of a specific type

查看:122
本文介绍了特定类型的可变模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个只接受无符号整数的可变参数模板。
然而,我不能得到以下工作。

I want a variadic template that simply accepts unsigned integers. However, I couldn't get the following to work.

struct Array
{
    template <typename... Sizes> // this works
    // template <unsigned... Sizes> -- this does not work (GCC 4.7.2)
    Array(Sizes... sizes)
    {
        // This causes narrowing conversion warning if signed int is supplied.
        unsigned args[] = { sizes... };
        // ...snipped...
    }
};

int main()
{
    Array arr(1, 1);
}

任何帮助。

编辑:如果你想知道,我想使用variadic模板来复制以下内容。

In case you're wondering, I'm trying to use variadic template to replicate the following.

struct Array
{
    Array(unsigned size1) { ... }
    Array(unsigned size1, unsigned size2) { ... }
    Array(unsigned size1, unsigned size2, unsigned size3) { ... }
    // ...
    Array(unsigned size1, unsigned size2, ..., unsigned sizeN) { ... }
};


推荐答案

我不知道为什么你希望工作。 Clang告诉我错误是未知类型名称'Sizes'在构造函数的声明。因为 Sizes 不是类型(或者更确切地说,模板包类型),所以它是一个模板包的值。

I'm not sure why you expected that to work. Clang tells me the error is unknown type name 'Sizes' in the declaration of the constructor. Which is to be expected, since Sizes isn't a type (or rather, a template pack of types), it's a template pack of values.

目前还不清楚你在这里做什么。如果你将整数值作为模板参数传递,那么构造函数参数是什么?

It's unclear what exactly you're trying to do here. If you pass integral values in as template parameters, what are the constructor parameters supposed to be?

/ strong>:使用您的新代码,您需要的是一个 static_cast< unsigned>()

struct Array
{
    template <typename... Sizes> // this works
    Array(Sizes... sizes)
    {
        unsigned args[] = { static_cast<unsigned>(sizes)... };
        // ...snipped...
    }
};

这篇关于特定类型的可变模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆