how to forward declare and then define a template function?

Hello,
I'm trying to forward-declare a template function outside of main() like this:

template <class typ> void memshift(typ arr [], int src, int dest, typ & cont);

I don't get any compile errors so hopefully that means it's right (??). But then how do I define the function inside main()? Like this?

1
2
3
template <class typ> void memshift(typ arr [], int src, int dest, typ & cont) {
    //function here
}


When I do that I get the following error: error: expected primary-expression before "template"

What have I missed/done wrong?
Last edited on
closed account (zb0S216C)
ausairman wrote:
I don't get any compile errors so hopefully that means it's right

If the compiler doesn't complain, it doesn't always mean there's nothing wrong.

ausairman wrote:
But then how do I define the function inside main()?

You can't define a function within another function. You need to either define the function body at the point of declaration, or define the body after main( ).

Wazzak
Last edited on
So how would I create this function:

1
2
3
void myfun(int input) {
  return input * SOMESTAT;
}


where SOMESTAT is a variable defined by another function?
closed account (zb0S216C)
ausairman wrote:
So how would I create this function:

1
2
3
void myfun(int input) {
  return input * SOMESTAT;
}


It's right in front of you; you've just written it. Unless you meant something else?

ausairman wrote:
where SOMESTAT is a variable defined by another function?

A variable defined within a function goes out of scope when the function returns.

Wazzak
So how would I create this function:

1
2
3
void myfun(int input) {
  return input * SOMESTAT;
}


where SOMESTAT is a variable defined by another function?


If somestat is an integer known at compile time, then can do with a template, but this does not seem particularly sensible. The alternative would be

1
2
3
4
5
int myfun_general(int input, int somestat)
  return input*somestat;
}

boost::bind(myfun_general, _1, valueForSomestat)


The bind returns a functor, that takes one argument, and when called, calls myfun_general(arg, valueForSomestat)
Topic archived. No new replies allowed.