Re: how to make a simple generic function... parameterized by
collection & value
On 2012-03-12 10:06, Daniel Kr?gler wrote:
Am 12.03.2012 02:46, schrieb Mark Summerfield:
[..]
// Generic function to make a set validator
template<template<typename T> class C, typename T>
Validator<T> make_set_validator(const C<T> &valid_items,
Validator<T> validate)
{
return [&valid_items,&validate](const std::string&s)->T{
const T&x = validate(s);
if (std::find(std::begin(valid_items), std::end(valid_items),
x))
return x;
throw ValueError("Invalid item '" + s + "'");
};
}
Here is the problem: Your function template make_set_validator should
return function pointer (according to the return type specification),
but it does instead return a lambda closure, which is a class type with
a function call operator overload. The important point to note here is
that this lambda closure has captures and this excludes it from being
stateless. Without the captures there would be the requirement that the
closure type provides a conversion function that would match your
constraints, but alas due to the captures this is not possible. Your
function should return std::function<T(const std::string&)> instead.
I should add the additional remark, that returning std::function<T(const std::string&)> instead would still leave the problem that you return a function object with invalid references: I strongly suggest to capture the Validator<T> validate by copy, not by reference to fix this problem.
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! ]