Re: how to ensure loop unrolling with template programming

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello Frank,

The following code works:

#include <iostream>
template <unsigned I>
struct repeat {
    template <typename F> void
    work(F f) { f(); repeat<I-1>().work(f); }
};
template <>
struct repeat<0> {
    template <typename F> void
    work(F) {}
};

void bar(){
  std::cout << "Hello World!" << std::endl;
}
void foo() {
  repeat<4>().work(bar);
}
int main()
{
foo();
}



Axel

On Mon, Jul 12, 2010 at 03:25:37PM +0200, Frank Winter wrote:
> Thanks for your reply!
>
> Your provided code doesn't seem to work:
>
> unroll.cc: In constructor repeat<I>::repeat(F):
> unroll.cc:4: error: declaration of repeat<(I - 1)> f shadows a parameter
> unroll.cc: In function void foo():
> unroll.cc:14: error: no matching function for call to repeat<4u>::repeat()
> unroll.cc:2: note: candidates are: repeat<4u>::repeat(const repeat<4u>)
>
> Frank
>
>
> On Fri, 9 Jul 2010, me22 wrote:
>
>> On 9 July 2010 02:29, Frank Winter <frank.winter@xxxxxxx> wrote:
>>>
>>> How can I make sure the compiler unrolls the loop and inlines all function
>>> calls? Do I have to use the preprocessor in my case?
>>>
>>
>> if you're *really* sure you know so much better than the heuristics, then:
>> - __attribute__((__force_inline__)) or something like that will inline the calls
>> - And change the loop to one at compile time using template specialization
>>
>> template <unsigned I>
>> struct repeat {
>>    template <typename F>
>>    repeat(F f) { f(); repeat<I-1>(f); }
>> };
>> template <>
>> struct repeat<0> {
>>    template <typename F>
>>    repeat(F) {}
>> };
>>
>> void bar();
>> void foo() {
>>    repeat<4>(bar);
>> }
>>
>> HTH,
>> ~ Scott
>>
>


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux