Simplest MetaLoop

I've written a simple template metaprogramming loop (below) using a
struct template which requires a loop index, and two function
signatures; one for the base (zero) case, and one for the inductive
(ith) case. As you can see below, I start things off with a call like
this:

Loop2<double (*)(double),  void (*)(int), 2 >::foo(f2,f1);

and the output is:

Hello from f1(2).
Hello from f1(1).
Hello from f2(0.123).

My question is, can I reconfigure this code so that I don't have to
explicitly specify the types of the two function pointers? For
example, something "like": Loop2<2>::foo(f2,f1);

Cheers,
P.

inline void   f1(int i)    { std::cout << "Hello from f1(" << i <<
")." << std::endl; }
inline double f2(double d) { std::cout << "Hello from f2(" << d <<
")." << std::endl; }

template<typename BaseFunc, typename InductiveFunc, int i>
struct Loop2 {
   static inline void foo(BaseFunc bFunc, InductiveFunc iFunc) {
     iFunc(i);
     Loop2<BaseFunc,InductiveFunc,i-1>::foo(bFunc,iFunc);
   }
};

template<typename BaseFunc, typename InductiveFunc>
struct Loop2<BaseFunc,InductiveFunc,0> {
   static inline void foo(BaseFunc bFunc, InductiveFunc iFunc) {
     bFunc(0.123);
   }
};

int main(int argc, char *argv[]) {
   Loop2<double (*)(double),  void (*)(int), 2 >::foo(f2,f1);
   return 0;
}

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
PGK
10/28/2009 5:13:50 PM
comp.lang.c++.moderated 10706 articles. 11 followers. allnor (8507) is leader. Post Follow

6 Replies
259 Views

Similar Articles

[PageSpeed] 0
On 29 Paź, 00:13, PGK <graham.k...@gmail.com> wrote:
> ... For example, something "like": Loop2<2>::foo(f2,f1);

You can use fact, that for functions template parameters can
be deducted by compiler. So when You change both function types
from being parameters of struct Loop2, to be parameters
of its member function foo, You get desired syntax (see example).

Regards,
Mateusz
>
> inline void   f1(int i)    { std::cout << "Hello from f1(" << i <<
> ")." << std::endl; }
> inline double f2(double d) { std::cout << "Hello from f2(" << d <<
> ")." << std::endl; }
>
> template<typename BaseFunc, typename InductiveFunc, int i>
> struct Loop2 {
>    static inline void foo(BaseFunc bFunc, InductiveFunc iFunc) {
>      iFunc(i);
>      Loop2<BaseFunc,InductiveFunc,i-1>::foo(bFunc,iFunc);
>    }
>
> };
template<int i>
  struct Loop2 {
     template<typename BaseFunc, typename InductiveFunc>
           static inline void foo(BaseFunc bFunc, InductiveFunc iFunc)
     {
       iFunc(i);
       Loop2<i-1>::foo(bFunc,iFunc);
     }

};

> template<typename BaseFunc, typename InductiveFunc>
> struct Loop2<BaseFunc,InductiveFunc,0> {
>    static inline void foo(BaseFunc bFunc, InductiveFunc iFunc) {
>      bFunc(0.123);
>    }
>
> };
  template<>
  struct Loop2<0> {
     template<typename BaseFunc, typename InductiveFunc>
       static inline void foo(BaseFunc bFunc, InductiveFunc iFunc)
     {
       bFunc(0.123);
     }

};
>
> int main(int argc, char *argv[]) {
>    Loop2<double (*)(double),  void (*)(int), 2 >::foo(f2,f1);
>    return 0;
>
> }
int main(int argc, char *argv[]) {
     Loop2<2 >::foo(f2,f1);
     return 0;

}


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Mateusz
10/29/2009 10:51:15 AM
On 29 oct, 00:13, PGK <graham.k...@gmail.com> wrote:
>
> Loop2<double (*)(double),  void (*)(int), 2 >::foo(f2,f1);
>
> and the output is:
>
> Hello from f1(2).
> Hello from f1(1).
> Hello from f2(0.123).
>
> My question is, can I reconfigure this code so that I don't have to
> explicitly specify the types of the two function pointers? For
> example, something "like": Loop2<2>::foo(f2,f1);

Sure, just use a template function that will be able to infer the
template parameters.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Mathias
10/29/2009 1:53:26 PM
On Oct 28, 11:13 pm, PGK <graham.k...@gmail.com> wrote:
> I've written a simple template metaprogramming loop [...]
>
> [Loop2 <double (*)(double), void (*)(int), 2>::foo (f2,f1);]
>
> My question is, can I reconfigure this code so that I don't have to
> explicitly specify the types of the two function pointers? For
> example, something "like": Loop2<2>::foo(f2,f1);

Sure, you can exploit function template argument deduction:

template <int i, typename BaseFunc, typename InductiveFunc>
void static_loop (BaseFunc fb, InductiveFunc fi) {
   Loop2 <BaseFunc,  InductiveFunc, i>::foo (fb, fi);
}

int main (int, char*[]) {
   static_loop <2> (f2, f1);
   return 0;
}

Regards,
Vidar Hasfjord


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Vidar
10/29/2009 1:54:34 PM
On 29 Okt., 00:13, PGK <graham.k...@gmail.com> wrote:
> I've written a simple template metaprogramming loop (below) using a
> struct template which requires a loop index, and two function
> signatures; one for the base (zero) case, and one for the inductive
> (ith) case. As you can see below, I start things off with a call like
> this:
>
> Loop2<double (*)(double),  void (*)(int), 2 >::foo(f2,f1);
>
> and the output is:
>
> Hello from f1(2).
> Hello from f1(1).
> Hello from f2(0.123).
>
> My question is, can I reconfigure this code so that I don't have to
> explicitly specify the types of the two function pointers? For
> example, something "like": Loop2<2>::foo(f2,f1);
>
> Cheers,
> P.
>
> inline void   f1(int i)    { std::cout << "Hello from f1(" << i <<
> ")." << std::endl; }
> inline double f2(double d) { std::cout << "Hello from f2(" << d <<
> ")." << std::endl; }

A function that returns a non-void result which normally exits
without return causes undefined behaviour.

> template<typename BaseFunc, typename InductiveFunc, int i>
> struct Loop2 {
>    static inline void foo(BaseFunc bFunc, InductiveFunc iFunc) {
>      iFunc(i);
>      Loop2<BaseFunc,InductiveFunc,i-1>::foo(bFunc,iFunc);
>    }
> };
>
> template<typename BaseFunc, typename InductiveFunc>
> struct Loop2<BaseFunc,InductiveFunc,0> {
>    static inline void foo(BaseFunc bFunc, InductiveFunc iFunc) {
>      bFunc(0.123);
>    }
> };
>
> int main(int argc, char *argv[]) {
>    Loop2<double (*)(double),  void (*)(int), 2 >::foo(f2,f1);
>    return 0;
> }

My first idea would be to split the iteration template parameter
from the actual functor types:

template<int i>
struct Loop2 {
    template<typename BaseFunc, typename InductiveFunc>
    static void foo(BaseFunc bFunc, InductiveFunc iFunc) {
      iFunc(i);
      Loop2<i-1>::foo(bFunc,iFunc);
    }
};

template<>
struct Loop2<0> {
    template<typename BaseFunc, typename InductiveFunc>
    static void foo(BaseFunc bFunc, InductiveFunc iFunc) {
      bFunc(0.123);
    }
};

int main() {
    Loop2<2>::foo(f2,f1);
}

HTH & Greetings from Bremen,

Daniel Kr�gler


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
ISO
10/29/2009 1:56:58 PM
On Oct 29, 1:13 am, PGK <graham.k...@gmail.com> wrote:
> My question is, can I reconfigure this code so that I don't have to
> explicitly specify the types of the two function pointers? For
> example, something "like": Loop2<2>::foo(f2,f1);

Just add this:
template<int N, typename BASE_FUNC, typename INDUCTIVE_FUNC>
void Repeat(BASE_FUNC bFunc, INDUCTIVE_FUNC iFunc) {
	Loop2<BASE_FUNC, INDUCTIVE_FUNC, N>::foo(bFunc, iFunc);
}

Which can be called like this:
    Repeat<2>(f2, f1);


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
tohava
10/29/2009 2:17:32 PM
PGK wrote:
> I've written a simple template metaprogramming loop (below) using a
> struct template which requires a loop index, and two function
> signatures; one for the base (zero) case, and one for the inductive
> (ith) case. As you can see below, I start things off with a call like
> this:
> 
> Loop2<double (*)(double),  void (*)(int), 2 >::foo(f2,f1);
> 
> and the output is:
> 
> Hello from f1(2).
> Hello from f1(1).
> Hello from f2(0.123).
> 
> My question is, can I reconfigure this code so that I don't have to
> explicitly specify the types of the two function pointers? For
> example, something "like": Loop2<2>::foo(f2,f1);

You could provide a simple helper function that re-orders the template
parameters and uses template argument deduction to deduce the function pointers
for you. As, for example:

    // ...

    template<int i, typename BaseFunc, typename InductiveFunc>
    void loop2_foo(BaseFunc bFunc, InductiveFunc iFunc)
    {
       Loop2<BaseFunc, InductiveFunc, i>::foo(bFunc, iFunc);
    }

    int main()
    {
       loop2_foo<2>(f2, f1);

       // ...
    }

Regards

Paul Bibbings

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Paul
10/30/2009 12:27:09 AM
Reply:
Similar Artilces:

Simplest getElementById question ever.
Why isn't this working? <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script language="javascript"> alert(document.getElementById('pst')); </script> </head> <body> <div id="subjects"> <form action="" method="get">1. Would you like to <div id="pst"> <a href="#">write a ...

The simplest way to intersect some intervals ?
Hi, Let's say I have this interval : A=[1:4]; And this matrix : X=[1 4; 2 3; 3 5;]; What I want is to intersect A with each line of X, each line being counted as an interval of integers : for example I want [1 4] to be processed as [1:4], [2 3] as [2:3] ect. intersect(A,[2:3]) works of course and returns : 2 3 but it is not possible to do something like intersect(A,X). How could I do this and, if possible, without using a for loop ? Hi Abel, I'm not sure what the desired output is. But I guess: A = 1:4; X =[1 4; 2 3; 3 5]; Y = [...

while -simplest question ;)
Hi All! This construction doesn't works and have a mistake while [ [ -z $PID ] && [ COUNT -ne 10] ] ; do..... How to write it properly? Appresiate for any help. On 2004-11-01, dmitry_kulinich <dkul@isd.dp.ua> wrote: > Hi All! > > This construction doesn't works and have a mistake > while [ [ -z $PID ] && [ COUNT -ne 10] ] ; > do..... > How to write it properly? while [ something ] && [ somethingelse ] ; do ... --Seb On 2004-11-01, dmitry_kulinich wrote: > Hi All! > > This construction doesn't works...

Code of "the simplest" Console in Assembly (HHHHHEEEELLLPP)
First of all, I can't speak english very well, so I'm so sorry for it I want the Assembly Code (I am using NASM) of the folowing situation:::: Well, what I wnat to do is a simple user interface, a "console" that allows user to write a command using the keyboard, and when the user press enter, the program will jump to the function of THIS command(there will be many commands) IMPORTANT: I CANT use syscalls like int0x21 or int0x80 because i am using ONLY bios interrupts like int 10 and int0x16(this program will be inside a boot loader/sector) Well, I think the command could...

I cannot compile the simplest program
I installed djgpp but I cannot compile the simplest program: #include <stdio.h> int main(void) { cout << "Hello World\n"; return 0; } I installed the 8 *.zip files: bnu2161b.zip djdev203.zip faq230b.zip gcc410b.zip gpp410b.zip mak3791b.zip rhid15ab.zip txi48b.zip Into C:\ProgramD\DJGPP\ Here is what I get: C:\ProgramD\DJGPP\Harry\Test>gpp -o test.exe test.cpp test.cpp: In function 'int main()': test.cpp:4: error: 'cout' was not declared in this scope C:\ProgramD\DJGPP\Harry\Test>set > environ.txt C:\ProgramD\DJGPP\Harry\Test>go32-v...

Simplest eth0 between 2 PCs?
Please lets confirm each stage. Like seeing the actual water-flowing-in-the-pipe. 1= plug cross-over cat-cable between PC1 <-> PC2. 2= PC1: ifconfig eth0 192.168.0.1 PC2: ifconfig eth0 192.168.0.2 See LEDs on PC1 connector light-up. What is the minimal command/s to confirm that each PC detects the other? What is the minimal command/s to transfer a file from 'src -> dest'? == TIA. On Mon, 30 Dec 2013 21:39:19 +0000 (UTC), Unknown wrote: > > Please lets confirm each stage. > Like seeing the actual water-flowing-in-the-pipe. > > 1= plug...

simplest problem ever
while ((mFood != "Y") || (mFood != "N")) { mFood = User.inputString("ENTER Y for food or N for no food"); } well i think the code should say what i want to do when i uinput Y i want the loop to end, same if i input N but the loop isnt ending help On Wed, 19 Apr 2006 20:03:07 +0100, Christo wrote: > while ((mFood != "Y") || (mFood != "N")) > { > mFood = User.inputString("ENTER Y for food or N for no food"); > } > > well...

Simplester MetaLoop
Now that I'm rewriting all applicable nested loops as template versions, I asked myself: why do I need to separate the base and inductive cases into two lexically separate template constructs? The "Hello World" that I'm building on looks something like this: template<int i> struct Loop1 { static inline void foo() { std::cout << "i is " << i << ", "; Loop1<i-1>::foo(); } }; template<> struct Loop1<0> { static inline void foo() { std::cout << "i is " << 0 << std::endl; ...

BPIs: The Simplest GUIs
The ease of use of graphical ("point-and-click") user interfaces (GUIs) to programs is counterbalanced by the increased complexity of writing and size of such GUI programs, using GUI libraries or toolkits such as GTK2+; indeed, for relatively simple programs, the GUI portion of the program is often more complicated and larger than the portion which does the basic work of the program. One method of simplifying the writing of GUI programs is to write and use a "visual", "what you see is what you get" (WYSIWYG), rapid application development (RAD) or GUI builder pro...

What software is the simplest to use on Motorola HC08 development?
I am trying to get started in mpu development. I have a Nitron HC08 development board and Metrowerks evaulation software but I am having a lot of trouble getting things to work. Every step is an effort. I think back to my days at school typing in the op codes with a keypad. It was error prone and repetitive but way more efficient then what I have been able to accomplish so far. Lots of changes from 14 years ago. The code I have written and flashed in, (verified it's there) never runs. The PC starts at $FFFF, goes to $1, then resets due to not being able to go into background mode,i...

Simplest way to use a named colour ?
Ok, in a UIL file, I can have something very simple such as: XmNbackground = color('Light Steel Blue', background) ; Somewhere in there, the colour gets translated to the right stuff and applied to the background of the widget and I don't have to lift a finger. Now, I want to dynamically set a colour inside a C program to either red , yellow or green. I've looked through example programs and couldn't find a single simple way of doing this. What is the simplest way to convert a standard named colour into a "Pixel" which I can then use as an arg...

Newbie: simplest way to connect several pcs in home
I want to connect several pcs (up to 5) to a central pc in a room. The connection will be used for data transfer in a low rate. The central pc sends and recieves from each surrounding pcs, only one byte, 30 times per a second. Considering 5 pcs the rate will be 1.2 kbps. Can anyone tell me what is the simplest way to do this? 2820794 001 The easiest/cheapest way would be to put a network card in each machine and then buy a hub/switch to connect them all together. You could also buy wireless network cards and a wireless access point, but this will be much more expensive. Agre...

scratch: Simplest explanation!
When I got no reply to my query of "what/how is scratch?", I assumed that people didn't want to admit 'playing' with infants' toys. Now I'll excuse them, because the INITIAL official documentation is poor. == scratch is a system to write programs/scripts by selecting WHOLE CONSTRUCTS, instead of single characters-from-a-keyboard. == It uses 3 panels: left: a pallette of constructs to select from [which are in 8 groups]; middle: an area where the constructs are assembled in suitable order, to build the script; right: the stage, where the scri...

Simplest bridge between JavaScript and SQLite
OS X now comes with SQLite libraries and headers. And various browsers (not to mention WebKit) incorporate JavaScript. I need to bridge the two: I want to write some web pages which run JavaScript which make SQLite calls on the server. This will provide me with a web-based interface to the SQLite databases on my own home computer. One way to do it would be to run PHP on my home computer, to write some accessor functions in PHP, and call them via AJAX. This has two bad aspects: one is that I will then need to rely on the interplay of five systems (HTML/CSS, JavaScript, AJAX, PHP a...

Simplest, easiest to use interface- OV or Netcool
Looking at a network with only a few nodes in it (5or 6). Mainly cisco routers but could be one or two 'other' things. Need a very simple interface that anyone could use to provide 'basic' management information. What would be best - HP OV or NetCool? Also, what about relative costs? Begin <1133256795.190076.113160@g49g2000cwa.googlegroups.com> On 2005-11-29, BertieBigBollox@gmail.com <BertieBigBollox@gmail.com> wrote: > Looking at a network with only a few nodes in it (5or 6). Mainly cisco > routers but could be one or two 'other' things. > &g...

Simplest MetaLoop
I've written a simple template metaprogramming loop (below) using a struct template which requires a loop index, and two function signatures; one for the base (zero) case, and one for the inductive (ith) case. As you can see below, I start things off with a call like this: Loop2<double (*)(double), void (*)(int), 2 >::foo(f2,f1); and the output is: Hello from f1(2). Hello from f1(1). Hello from f2(0.123). My question is, can I reconfigure this code so that I don't have to explicitly specify the types of the two function pointers? For example, something "like": Loop...

The simplest Assembler
After finishing the simplest CPU, now is the time to test. We may have to resort to binary coding and students must learn how to do it but students should also be exposed to higher programming languages. google search: http://sourceforge.net/projects/sgasm/files/latest/download Not so simple. Written in C. http://www.embeddedrelated.com/usenet/embedded/show/43765-1.php Forum for writing a simple assembler. There is an interesting discussion on flex, bison , C in writing the assembler. From my experience, flex is redundant. It is too difficult to learn, let alone remember. N...

Simplest latex class
I want to create a pdf file with some jpg images in it, I am doing it by using pdflatex and put images in it, I think th article class is an overkill for this purpose, is there a simpler class file I can use. totaljunk.emails@gmail.com wrote: > I want to create a pdf file with some jpg images in it, I am doing it > by using pdflatex and put images in it, I think th article class is an > overkill for this purpose, is there a simpler class file I can use. > well the most minimal class might be 'minimal' but how does it matter? your pdf-file cannot see the difference anyw...

what is the simplest way of having a signed applet?
My applet wants to list the local files and directories (using JFileChooser), so I thought I should sign the applet. I use this to sign my applet: javac SimplePaint.java jar cvf SimplePaint.jar SimplePaint.class keytool -delete -alias SimplePaint keytool -genkey -alias SimplePaint -validity 365 jarsigner SimplePaint.jar SimplePaint Is there a faster way to do it? I don't want to go through the questions each time. Thanks!! On 2 May 2004 06:08:00 -0700, b83503104@yahoo.com (b83503104) wrote or quoted : >javac SimplePaint.java >jar cvf SimplePaint.jar SimplePaint.class the foll...

simplest LISP interpreter
HI all, Anyone knows the simplest LISP interpreter, I want to know how it works. Any help appreciated! Binary "Binary" <binary.chen@gmail.com> writes: > HI all, > > Anyone knows the simplest LISP interpreter, I assume this is a question. I believe the answer is, approximately: (defun lisp () (write-line "Storage exhausted.")) > I want to know how it works. The way it works is by exploiting the fact that implementations are permitted to have resource limitations of various kinds, and that if you make sure such limitations come into play early ...

Simplest possible node
I hope this isn't out of context of this group, if it is, I'm sorry for the spam. I'm looking for the simplest possible hardare implementation that I can connect via cat5 ethernet cable to my router that my router will recognize as a node on the network, and be willing to send it data, even if that data is simply dropped on the floor, so to speak. Is it possible to just use a power supply and ground to set certain pins on the cable a constant high or low? Any help is greatly appreciated. Thanks. bmearns wrote: > I hope this isn't out of context of this gro...

Is a^-2 in simplest form? (Hoist on my own petard!)
The problem was a^4*a^-6, I said a^-2, my software (http://www.theoryyalgebra.com/) said it was not simplest form, but 1/a^2 was. Who is right?!!! Mind you the target is an educational setting, if that matters. I think my software is right, but I started to wonder. cheers, kenny --- http://www.theoryyalgebra.com/ Kenny <kentilton@gmail.com> wrote on Sat, 16 Aug 2008: > The problem was a^4*a^-6, I said a^-2, my software > (http://www.theoryyalgebra.com/) said it was not simplest form, but 1/a^2 > was. Who is right?!!! Mind you the target is an educational setting, if >...

Simplest MCU or SOC for linux
I think the simplest 32-bit core that can run Linux with MMU is the ARM7-based MCUs. Am I correct? And where can I get such MCUs and SOCs for educational and experimental purposes. Performance is not a priority, price and simplicity is. Ideally I would have gone with the Am386 from AMD if they still had those. The elan586 is a bit expensive. Motorolla's 68030-based MCUs are a bit too specialized but look better than the x86 based MCUs. I know nothing about the ARM or MIPS based cores. The SSH3 based MCUs are also I believe cheap but I havent investigated those in favor of t...

Simplest midi sequencer
Hi Folks, Does anyone know what is the simplest most basic midi sequencer for PC? Something akin to Windows Sound Recorder.. Preferably free or cheap. ie. just give it a filename, click record and stop when you've finished. Know messing about creating empty tracks, entering punch in and out points, setting track parameters. I have any number of more advanced sequencers, but just need something quick and simple to use for MIDI file record and playback of unedited live performances. TIA -- Sabina There wee stand alone midi recorders made sort of like a tape recorder, but used a disk. ...

Experience designing the simplest CPU
With a textbook, good Altera Quartus II tutorial, from the vendor, Terasic for the DE2-115, I thought I can easily design and test the mano risc cpu. In just a few hours, finished, but on compiling, no output at all. Spent the next few hours deleting parts one by one, and yet, until only the PLL oscillator left, still no output. The PLL was the same as in the tutorial and yet no problem previously. Whatever the probem, it was not due to the design. Must be some sort of licensing problems. I use the free web edition of the Altera Quartus using the Megawizard functions, in Verilog. Th...