前提:
在稍微使用了可变参数模板之后,我意识到实现稍微超出简单的元编程任务的任何东西很快变得非常麻烦.特别是,我发现自己希望的执行方式上的参数包一般操作如迭代,拆分,循环在一个std::for_each样的方式,等等.
在观看了由安德烈Alexandrescu的本次讲座由C++和超越2012年的愿望static if成C++(从借来构建d编程语言),我的感觉是某种static for会来得心应手,以及-我觉得更多的这些的static结构能带来好处.
所以我开始想知道是否有办法为变量模板函数(伪代码)的参数包实现类似的东西:
template<typename... Ts>
void my_function(Ts&&... args)
{
static for (int i = 0; i < sizeof...(args); i++) // PSEUDO-CODE!
{
foo(nth_value_of<i>(args));
}
}
Run Code Online (Sandbox Code Playgroud)
哪个会在编译时被翻译成这样的东西:
template<typename... Ts>
void my_function(Ts&&... args)
{
foo(nth_value_of<0>(args));
foo(nth_value_of<1>(args));
// ...
foo(nth_value_of<sizeof...(args) - 1>(args));
}
Run Code Online (Sandbox Code Playgroud)
原则上,static_for将允许更精细的处理:
template<typename... Ts>
void foo(Ts&&... args)
{
constexpr s …Run Code Online (Sandbox Code Playgroud) c++ iteration template-meta-programming variadic-templates c++11
当我偶然发现这个问题时,我正在尝试使用C++ 0x可变参数模板:
template < typename ...Args >
struct identities
{
typedef Args type; //compile error: "parameter packs not expanded with '...'
};
//The following code just shows an example of potential use, but has no relation
//with what I am actually trying to achieve.
template < typename T >
struct convert_in_tuple
{
typedef std::tuple< typename T::type... > type;
};
typedef convert_in_tuple< identities< int, float > >::type int_float_tuple;
Run Code Online (Sandbox Code Playgroud)
当我尝试输入模板参数包时,GCC 4.5.0给出了一个错误.
基本上,我想将参数包"存储"在typedef中,而无需解压缩.可能吗?如果没有,是否有一些理由不允许这样做?
应用程序图像的实现具有通过由编译器计算其指数的函数初始化它的元素,并已存储在数据部分的结果的C++ 11阵列的一种方式(.RODATA)是使用模板,部分特和constexpr如下:
#include <iostream>
#include <array>
using namespace std;
constexpr int N = 1000000;
constexpr int f(int x) { return x*2; }
typedef array<int, N> A;
template<int... i> constexpr A fs() { return A{{ f(i)... }}; }
template<int...> struct S;
template<int... i> struct S<0,i...>
{ static constexpr A gs() { return fs<0,i...>(); } };
template<int i, int... j> struct S<i,j...>
{ static constexpr A gs() { return S<i-1,i,j...>::gs(); } };
constexpr auto X = S<N-1>::gs();
int main()
{
cout << …Run Code Online (Sandbox Code Playgroud)