Click here to Skip to main content
11,705,610 members (51,299 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C++ C++11 Lambda
I want to do something like this

template <typename T, typename IncrementorT = [] (T& val) -> T& {val++; return val;} >
class RangeAllocator...

where IncrementorT is a user replaceable functor that RangeAllocator will use to increment values. I know I can do it using a struct but I'm interested to play with the new c++11 toys.
Posted 30-Apr-13 20:48pm
Maximilien at 1-May-13 8:23am
Dear mother of god!!!
Volynsky Alex at 1-May-13 10:01am
Let's read the following post:
jsolutions_uk at 1-May-13 10:11am
just beat me to it :)
Volynsky Alex at 1-May-13 11:17am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

I'm not sure it is possible with lambdas, it's looking rather like a polymorphic lambda. check here[^]. I just don't think lambdas were intended to be used in the context of template based generic programming.

The closest I have managed to get to implementing what you have above is this:

template <typename T>
T& func(T& val)
    return val;
template <typename T, T&(*Func)(T&) = func<T>>
class SomeClass
    SomeClass() : val(0) {};
    void CallIt()
        std::cout << "val before call = " << val << std::endl;
        std::cout << "val after call = " << val << std::endl;
    T val;  
int main(int argc, char* argv[])
    SomeClass<int> instance;
	return 0;

But then that doesn't help with your original question wrt playing around with lambdas, and it is also probably just as simple to use a functor in my particular example.

I'd love to here if someone managed to do this, or by using std::function as a wrapper for a lambda.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

I know you can use functions as template parameters[^]. I suppose it could work with lambdas, but I have not tried myself.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 229
1 Sergey Alexandrovich Kryukov 100
2 Inimicos 60
3 ProgramFOX 50
4 Richard MacCutchan 45
0 OriginalGriff 9,053
1 Sergey Alexandrovich Kryukov 8,347
2 CPallini 5,189
3 Maciej Los 4,726
4 Mika Wendelius 3,626

Advertise | Privacy | Mobile
Web04 | 2.8.150819.1 | Last Updated 2 May 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100