相关疑难解决方法(0)

如何在可变参数模板函数的异构参数包上进行泛型计算?

前提:

在稍微使用了可变参数模板之后,我意识到实现稍微超出简单的元编程任务的任何东西很快变得非常麻烦.特别是,我发现自己希望的执行方式上的参数包一般操作迭代,拆分,循环在一个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

77
推荐指数
3
解决办法
6371
查看次数

是否可以"存储"模板参数包而不扩展它?

当我偶然发现这个问题时,我正在尝试使用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++ templates variadic-templates c++11

71
推荐指数
2
解决办法
2万
查看次数

C++ 11:具有对数评估深度的编译时数组

应用程序图像的实现具有通过由编译器计算其指数的函数初始化它的元素,并已存储在数据部分的结果的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)

c++ c++11

17
推荐指数
1
解决办法
1178
查看次数