Question of template

Could template work with std::tr1::function and lambda?
1
2
3
4
5
6
7
8
9
10
11
12
template<typename anyFunctor = printTxt> //printTxt is somekind of functor
void testFunctor()
{
  anyFunctor f;
}

void testFunctor2()
{
  testFunctor(); //ok
  std::tr1::function<void(size_t)> f = [](size_t& acc2){ acc2 = 100;};
  testFunctor<f>();//error
}


the error messages is
error: 'f' cannot appear in a constant-expression error: no matching function for call to 'testFunctor()'

Thank you very much
Last edited on
f is not a type, you can't put it in the template like that.

You'll need to pass the type of f to testFunctor:
testFunctor<std::tr1::function<void(size_t)>>();

Note that the function does not actually do anything...maybe you wanted to pass the functor as a parameter or something?
Thanks, looks like I have to define a type and put it in the template
there are still other questions

1 : if type anyFunctor need 3 arguments to initialize it, what should I do?
Do I have another way to make this become more adaptable except
of passing strategies like parameter(the way of stl did)

2 : if type anyFunctor need to accept different number of variables, how could I make it adaptable?
1
2
3
  anyFunctor f;
  f(1 , 2); //ok
  f(1, 2, 3); //ok too 

Do I need to pass it as arguments if I want to implement it by std::tr1::bind?
Thank you very much
Last edited on
1) Then in your function you would have to initialize it with those 3 arguments.

2) Generally it is the function (in this case, testFunctor()) that places constraints on the functors that are accepted by it. If the user passes a type that doesn't work as you call it in the function, they will get an error message:

1
2
3
4
5
6
7
8
9
template<class Functor_type>
void foo(Functor_type f) {
    f(1, 2);
}

int main() {
    foo([&](int x, int y, int z) {std::cout<<x+y+z; }); //error, the lambda here needs 3 args
    //but when the template is generated it is only called with two
}
According to your conclusions, do you mean if I want to treat "template as strategies"
It could not adapt to arbitrarily arguments?
If I want the "strategies(template)" accept arbitrarily arguments, I have to use the way like stl did?
Thank you
Last edited on
Topic archived. No new replies allowed.