0

So I have the following code:

enum class UnitType { yearType, monthType, dayType };

struct NoValidation {
        void operator()(int x) const {}
};

template <UnitType U, typename Validator=NoValidation>
class Unit {
        public:
                explicit Unit(int v) : value(v) {
                        Validator()(v);
                }
                int query() const { return value; }
        private:
                int value;
};

auto validateYear = [](int x){
        if(x < 0)
                throw std::invalid_argument("Year is negative");
};

using Year = Unit<UnitType::yearType,decltype(validateYear)>;
using Month = Unit<UnitType::monthType>;
using Day = Unit<UnitType::dayType>;

The declaration of Month and Day works fine, but Year does not.

error: no matching constructor for initialization of '(lambda

Is there any way that I could modify this code to work with lambdas? Without passing the lambda as a parameter to the constructor, just as a template parameter. In theory a lambda is just syntactic sugar for a Functor, so why doesn't this work?

Edit I'd like to open this issue so that @Yakk can post his solution directly too my question.

Knarf
  • 1,282
  • 3
  • 12
  • 31
  • 1
    Why can't you just use a struct? It would only be slightly more verbose than the lambda. – Nicol Bolas Sep 29 '16 at 13:06
  • In your constructor. Instead of constructing it there, receive it as a parameter `Unit(int v, Validator val = {})` Problem solved! – Guillaume Racicot Sep 29 '16 at 13:07
  • 2
    @Jarod42 Bah, closing a C++14 question as a duplicate of a C++11 question makes my [new answer](http://stackoverflow.com/a/39771222/1774667) not as valid. The short bit is that the duplicate target answers say "no, you cannot do it", when you actually can at least in this poster's case. Guilluame's solution is also good. – Yakk - Adam Nevraumont Sep 29 '16 at 13:11
  • 1
    @LogicStuff A C++14 question is not a duplicate of the C++11 question, as there might be other solutions for C++14. – Knarf Sep 29 '16 at 13:17
  • This question really does want a good [mcve], with the full error message (with line number, etc). I'm nominating to re-open, but be aware that it still needs improvement. – Toby Speight Sep 29 '16 at 13:46

0 Answers0