非类型可变函数模板在C ++ 11 [英] Non-type variadic function templates in C++11

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

问题描述

我看到了一个博文,它使用非类型可变模板(目前不支持gcc,只有clang)。

 模板< class T,size_t ... Dimensions> 
struct MultiDimArray {/ * ... * /}

后编译示例很好,但我没有得到它使用函数模板。 p>

任何人都可以帮助找出正确的语法(如果存在)?

  int max(int n){return n; } // end condition 

template< int ... N> //替换int ...用typename ...工作
int max(int n,N ... rest)//!错误:未知类型名称'N'
{
int tmp = max(rest ...);
return n< tmp? tmp:n;
}

#include< iostream>
int main()
{
std :: cout< max(3,1,4,2,5,0)<< std :: endl;
}


解决方案

和非类型名称。

您可以 可能在函数中使用可变非非类型模板,但不能作为(非模板) )arguments:

  template< int N,int ... Rest> 
int max()
{
int tmp = max return N< tmp? tmp:N;
}





  std :: cout<< max< 3,1,4,2,5,0>()< std :: endl; 

...虽然我没有测试过,但我不确定 >这应该工作,因为你需要有一个部分专业化作为基础案例。你可以通过分派到一个部分专用的结构来解决这个问题:

  template< int N,int ... Rest& 
struct max_t {
static int const value = max_t< Rest ...> :: value> N? max_t< Rest ...> :: value:N;
};

template< int N>
struct max_t< N> {
static int const value = N;
};


template< int ... NS>
int max()
{
return max_t< NS ...> :: value;
}

这将工作。


I saw a blog post which used non-type variadic templates (currently not supported by gcc, only by clang).

template <class T, size_t... Dimensions>
struct MultiDimArray { /* ... */ };

The example in the post compiles fine but I failed to get it to work with function templates.

Can anyone help figuring out the correct syntax (if such exists)?

int max(int n) { return n; } // end condition

template <int... N> // replacing int... with typename... works
int max(int n, N... rest) // !! error: unknown type name 'N'
{
    int tmp = max(rest...);
    return n < tmp? tmp : n;
}

#include <iostream>
int main() 
{
   std::cout << max(3, 1, 4, 2, 5, 0) << std::endl;   
}

解决方案

You are simply confusing type names and non-type names. What you want simply doesn’t work.

You can probably use variadic non-type templates in functions, but not as (non-template) arguments:

template <int N, int... Rest>
int max()
{
    int tmp = max<Rest...>();
    return N < tmp ? tmp : N;
}

std::cout << max<3, 1, 4, 2, 5, 0>() << std::endl;

… although I haven’t tested this and I’m not sure how this should work given that you need to have a partial specialisation as the base case. You could solve this by dispatching to a partially specialised struct:

template <int N, int... Rest>
struct max_t {
    static int const value = max_t<Rest...>::value > N ? max_t<Rest...>::value : N;
};

template <int N>
struct max_t<N> {
    static int const value = N;
};


template <int... NS>
int max()
{
    return max_t<NS...>::value;
}

This will work.

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

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