C ++ 11中的固定长度可变参数包 [英] Fixed Length Variadic Parameter Packs in C++11

查看:265
本文介绍了C ++ 11中的固定长度可变参数包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用C ++ 11实现一个广义的n维向量类。理想情况下,我想提供类型T和向量的维数n,并让构造函数接受适当数量的参数。

I'm attempting to implement a generalized n-dimensional vector class using C++11. Ideally, I'd like to provide the type "T" and number of dimensions "n" of the vector and have the constructor accept the appropriate number of arguments.

,我一直无法找到一个方法来允许一个参数包的模板指定的固定长度。

Unfortunately, I've been unable to find a way to allow a template-specified fixed length of a parameter pack.

我正在寻找的是像

template<typename T, size_t n>
class Vector {
public:
    Vector(T... values /* values is exactly n parameters long */);

    ...
};

是否可以这样做?

推荐答案

你可以使用std :: enable_if:

Well, you can use std::enable_if:

template <typename... Args,
    typename = typename std::enable_if<
        sizeof...(Args) == n
    >::type>
explicit Vector(Args&&... values) : _data{ std::forward<Args>(values)... } {}

它会影响可能接受除n之外的Args大小的构造函数。

It will shadow constructors that may accept size of Args other than n.

这篇关于C ++ 11中的固定长度可变参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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