2

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; 
}
dgrat
  • 2,036
  • 4
  • 19
  • 39

1 Answers1

5
  1. accumulate_for<n>::get is a member function template, so you have to specify template argument when calling it.

  2. You need to use template keyword to indicate that get and run (which are both dependent names) are templates.

e.g.

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

LIVE

For more info about the usage of the template keyword, refer to Where and why do I have to put the “template” and “typename” keywords?

songyuanyao
  • 147,421
  • 15
  • 261
  • 354
  • I dont get why template keyword is necessary. The compiler should see this?! – dgrat Jul 13 '17 at 09:19
  • 1
    @dgrat Have you checked the link? In short, without that, for `get`, the compiler won't regard `get` as a template name, then `` ?), which has a static data member named `get` then make `accumulate_for::get < something` valid. – songyuanyao Jul 13 '17 at 09:22