一个特定类型的可变模板参数 [英] Variadic template parameters of one specific type

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

问题描述

为什么在可变参数模板包中不允许使用特定类型?

 类型名T> 
class Foo
{
public:
template< typename ...值>
void bar(Values ... values)
{
}

template< T ...值> < - 语法错误
void bar(T ... values)
{
}

template< int ... values> < - 语法错误
void bar(int ... values)
{
}
};

不是的理由是什么?
$ b $


  • std :: initializer_list< T> 不缩小类型和 {} -brace语法

  • <递归特征,分别检查所有类型:请参见此处

解决方案

这是允许的,实际上,你只是使用它错了。 T ... int ... 是非类型参数包,其元素是值,因此您可以



正确用法示例:

 模板< int ... Is> 
struct IntPack {};

IntPack< 1,2,3> p;

  template<类型名T> 
struct Foo
{
template< T ... Ts>
void bar()
{
}
};

int main()
{
Foo< int> F;
f.bar< 1,2,3>();
}

另一个例子是 std :: integer_sequence


Why there is no specific type allowed in a variadic template pack?

template< typename T >
class Foo
{
public:
    template< typename... Values >
    void bar( Values... values )
    {
    }

    template< T... values >            <-- syntax error
    void bar( T... values )
    {
    }

    template< int... values >          <-- syntax error
    void bar( int... values )
    {
    }
};

Whats the rationale in not allowing this?
Are there proposals for this?


Note: alternatives would be

  • std::initializer_list< T > without narrowing of types and the { }-brace-syntax
  • a (ugly) recursive trait that checks all types seperately: see here

解决方案

It IS allowed, actually, you're just using it wrong. T... and int... are non-type parameter packs and their elements are values, so you can't use them as type specifiers (and you can't deduce them from a function call).

An example of correct usage:

template<int... Is>
struct IntPack {};

IntPack<1,2,3> p;

or

template< typename T >
struct Foo
{
    template< T... Ts>
    void bar()
    {
    }
};

int main()
{
    Foo<int> f;
    f.bar<1,2,3>();
}

Another example would be std::integer_sequence.

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

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