Simplest MetaLoop

  • Permalink
  • submit to reddit
  • Email
  • Follow


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
Reply PGK 10/28/2009 5:13:50 PM

See related articles to this posting


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
Reply 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
Reply 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
Reply 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
Reply 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
Reply 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
Reply Paul 10/30/2009 12:27:09 AM
comp.lang.c++.moderated 10664 articles. 10 followers. Post

6 Replies
222 Views

Similar Articles

[PageSpeed] 24


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

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; ...

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...

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...

How to get the simplest NumberFormats
HelloI would like to format numbers (doubles) for display. I want to use the methods NumberFormat.setMinimumFractionDigits() for rounding, but I am annoyed by the Locale.How can I get rid of the Locale formatting and get back a simple number format (with a dot as decimal separator).Expected: 1234567.89US: 1,234,567.89My Own Locale: 1'234'567.89How to get rid of all these ' and , ?Thanks Phil On 12.03.2007 12:11, Philipp wrote:> Hello> I would like to format numbers (doubles) for display. I want to use the > methods NumberFormat.setMinimumFractionDigits() for rounding, but ...

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 QoS for VoIP
Hi, I have two PBXs in two different sites, exchanging communication by VoIP across a network link. I'd like to setup some QoS for phone traffic (good idea, isn't? :-)) but I'm not a "guru" of QoS. Some preliminary suggestion? Good reading? A simple setup? Do I need to setup QoS only between routers or along the whole chain of devices? Thanks in advance Mimmus P.S. Sorry for my bad english Mimmus, While I've never dealt with Qos for voice over IP, I've worked with it for video over IP purposes quite a bit.. The first thing I would to id examine all of the l...

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...

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. ...

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...

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 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...

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...

Simplest P2P program?
Can someone direct me to a very small windows app/program which will allow voice chat with a peer? Ie program simply takes the IP address of a peer to contact and establishes a VOIP session. No text chat, no address book etc. Hello dexx, Tuesday, May 3, 2005, 5:18:51 AM, you wrote: > Can someone direct me to a very small windows app/program which will try Skype. feel free to test with me: teslaua www.skype.com -- Best regards, nntp mailto:a@a.com "dexx" <D3xx@hotmail.com> wrote in message news:1115086731.620086.1638...

Simplest processor to emulate?
I'm curious - of all the various CPUs that have been emulated to date, which one is considered the simplest to work with? Maybe it comes down to which has the smallest instruction set, I don't know. Bottom line, I guess I'm curious which one takes the least processing power to emulate as well as which can be done with the smallest amount of source code. To that end, then which machine (console, arcade, whatever...) might be the machine that can be singly emulated with the lowest requirements for host machine to run the emulator on? If any of that made sense :), ...

Simplest hardware node
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'm looking for the simplest possible hardare implementation that I can > connect via cat5 ethernet cable to my router that my route...

Simplest Makefile.PL
Hi, I've got a cute little ASCII plotting module that I'd like to release to CPAN, but I don't know how to create a Makefile.PL file. I've looked at some examples but they are too complex and confusing. Could someone point me to some documentation or post a barebones Makefile.PL? Thanks in advance. Inventor coughed up some electrons that declared: > Hi, I've got a cute little ASCII plotting module that I'd like to > release to CPAN, but I don't know how to create a Makefile.PL file. > I've looked at some examples but they are too complex and confusi...

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 solution for offscreen rendering
Hi! I just want to know if there is a solution to make multiOS (and graphic card independent) offscreen rendering in opengl. i've find some solution but for some hardware only or only under windows. thanks in advance for the answer. -- Ceci est une signature automatique de MesNews. Site : http://mesnews.no-ip.com Try a Render_to_texture ... you'll lose a bit in quality ( limit your texture size to 512*512 for backward comp. with older cards ), but that's the simplest multiOS hack i can think of ! [kohai ] "3dsman" <3dsman@free.fr> a �crit dans le mes...

simplest webservice client ever
i have created a simple web service using tomcat and axis 1.4it just has one method that returns the string hello worldi want create a client that would use this webservicei tried some tutorials on the web but couldnt do itcan you please help "ali" <ali4ever4@gmail.com> wrote in message news:1178353500.726325.143800@h2g2000hsg.googlegroups.com...>i have created a simple web service using tomcat and axis 1.4>> it just has one method that returns the string hello world>>> i want create a client that would use this webservice>> i tried some tutorials on the...

Simplest and most reliable printer for an iMac?
My siblings and I bought our 80-some year old mother a new iMac for Christmas, and her Epson Stylus Color 740 -- unsupported by Snow Leopard -- is now junk. So we'd like to hear recommendations for a new printer. We're not interested in speed or ultra-high quality photos or multi-function; we're looking for robustness and simplicity above all. We'd like our mother to be able to change the ink cartridges by herself! Beyond that, we're looking for a major brand with good OS X support, and not overly expensive (especially the ink). Under $200 certainly, and unde...

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 = [...

simplest code to parse this string
I need to parse and convert a specific format string, example given below, into its various numeric fields. Although I've kludged a quick and dirty solution which works, it doesn't seem as compact as it might be in standard Forth-94. Will take suggestions .... The high level word, call it PARSE-LOG-LINE, should take the address and count of a string and parse and convert the fields and store them into the respective variables. Restrictions: use just standard Forth-94 and no externally defined words. This exercise is in connection with some Forth code I will release here soon. -- Examp...

Simplest Linux Driver Needed..
Hello, Sorry for the wide broadcast. I am studying Linux Device Driver and would like to have some good or simple samples/web site to reduce the learn curve. May someone help me on this? Thanks, Horse. Little.Horse wrote: > Hello, > > Sorry for the wide broadcast. I am studying Linux Device Driver and would > like to have some good or simple samples/web site to reduce the learn curve. > May someone help me on this? Thanks, > If you do not already have it, get the book Alessandro Rubini and Jonathan Corbet, Linux Device Drivers, 2nd Edition, O'Reilly, ISBN 0-596...

The simplest php webapp ever
The simplest php webapp ever http://morecute.com ...