How to use lambda as template argument with default value in C ++?

I want to do a simple thing:

void DoUntil(auto predicate = [] { return false; });

Obviously this does not work - I need to use the template argument:

template <typename P>
void DoUntil(P predicate = [] { return false; });

But this statement does not work either - Clang gives an error:

error: there is no suitable function to call ... note: candidate template is ignored: could not output template argument 'P'

If I call the function without arguments, some compiler cannot deduce the type from the default argument:

int main() { DoUntil(); }

I do not want to use std::function<>it in any way.

Are there any other possible solutions to my problem?

+6
source share
2 answers

. , :

void DoUntil() ;

template <typename P>
void DoUntil(P predicate) ;

, :

void DoUntil() { DoUntil([] { return false; }); }

, , , . lambdas , T , T :

template <typename T>
void Foo(T t = 3);

T <typename T = int>.

WhiZTiM, , -, decltype. , , , lambdas , .

+6

- (, copy/move, ). -, :

namespace detail{ auto predicate = [] { return false; }; }

template <typename P = decltype(detail::predicate)>
void DoUntil(P pred = detail::predicate);

, . -:

namespace detail{
    struct DefaultPredicate{ bool operator()() const { return false; } };
}

template <typename P = detail::DefaultPredicate>
void DoUntil(P predicate = P{});

, .

+3

Source: https://habr.com/ru/post/1014942/


All Articles