jeudi 13 juillet 2017

Simple (recursion) variadic template "accumulate_for" function with compile problems

I want to write a variadic template or const expressions which 1) execute a template functor N times and 2) accumulates the result. I wrote a small example which actually fails compilation as soon as I move the function which gets executed into a template functor. I have the feel I am close to the solution, but maybe I am wrong.

#include <iostream>
#include <string>

struct F {
    template <int id>
    static int run(int val) {
        return id * val;
    }
};

template<unsigned int n>
struct accumulate_for
{
    template <class Funct>
    static int get(int val) {
        return 
        (
        accumulate_for<n-1>::get(val) 
        + 
        Funct::run<n>(val)
        );
    }
};

template<>
struct accumulate_for<0>
{
    template <class Funct>
    static int get(int val) {
        return 0;
    }
};

int main()
{
    std::cout << accumulate_for<3>::get<F>(1) << std::endl; 
}

Aucun commentaire:

Enregistrer un commentaire