I have this C++ function object:
static unsigned long long const FNV_OFFSET_BASIS = 14695981039346656037ul;
static unsigned long long const FNV_PRIME = 1099511628211ul;
struct fnv_hash {
typedef unsigned long long value_type;
fnv_hash( value_type *result ) {
_result = result;
*_result = FNV_OFFSET_BASIS;
}
void operator()( char c ) { // Fowler–Noll–Vo FNV-1a hash function
*_result ^= c; // see: https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function
*_result *= FNV_PRIME;
}
private:
value_type *_result;
};
that can be used like:
std::string const message = "hello, world";
hash::value_type hash_val;
std::for_each( message.begin(), message.end(), fnv_hash( &hash_val ) );
If I wanted to convert the function object to a lambda, there's the problem of initializing the captured variable hash_val to FNV_OFFSET_BASIS only when the underlying, compiler-generated lambda object is constructed. The only thing I can think of to do that is using yet another lambda:
std::for_each( message.begin(), message.end(),
[&hv = [&hash_val]() -> decltype((hash_val)) {
return hash_val = FNV_OFFSET_BASIS; // Initialize and return reference to hash_val.
}() // Call the inner lambda.
]( char c ) {
hv ^= c;
hv *= FNV_PRIME;
}
);
This works, but is there a cleaner way to to this?
Note: the example given is for pedagogical reasons only. The point of the question is how one can "initialize" a lambda in general --- and not how to solve this particular hash example.
Note: "It can't be done" is an acceptable answer. I want an answer in the event someone asks me a question similar to: what are the case(s) where one ought to still use a function object as opposed to a lambda?
FNV_OFFSET_BASISanyway, won't it be easiest to simply initializehash_valbefore passing it to the lambda?std::accumulate...std::accumulatefor this particular example really isn't the point of the question.fnv_hash? Since it's nicely encapsulated, it'd require some effort to misuse.