Reputation: 741
First of all, I know I could use templated class/functor, but that is not what I want.
Here is the lambda:
auto lambda = [] (auto var) {
decltype(var) x;
//do stuff with x but nothing with var
};
The problem is I receive the warning C4100(unreferenced formal parameter). I also know I could use tricks such as disabling the warning and enabling it again after the lambda or using macros such as UNREFERENCED_PARAMETER, but that is cheating.
Is there any way I could accomplish that?
An ideal code would look like this:
template <typename T>
auto lambda = [] () {
T x;
//do stuff with x
};
Upvotes: 20
Views: 6563
Reputation: 41301
In fact, in C++14 you can create "template lambdas" using exactly the syntax you want, but only in namespace scope:
// (1)
template <typename T>
auto l = [] () {
T x;
};
int main() {
l<int>();
}
It's not a generic lambda, it's a variable template, but you can even create generic template lambda:
template <typename T>
auto l = [] (auto y) {
T x = 42;
std::cout << x + y << std::endl;
};
But there is a downside: it seems that among current compilers only Clang supports this.
Update: Since this can only be done in namespace scope, if your lambda has no arguments, or doesn't have auto
arguments (that is, it's not generic), it can be replaced by a function without requiring even any C++11 features, not mentioning C++14. If such lambda has captures, they can capture only global variables, so the corresponding function may just use the same variables or their copies. Thanks to @JasonR for pointing this out:
// effectively the same as (1)
template <typename T>
void l() {
T x;
}
Upvotes: 17
Reputation:
Do not use lambda:
template<typename T>
struct Functor
{
void operator () () { T var; ... }
}
A lambda is nothing else, a compiler generated functor.
Upvotes: 7
Reputation: 67
No, a generic lambda cannot have no arguments because it doesn't have arguments to deduce a type from. You will have to use the fallback templated functor.
Upvotes: 3
Reputation: 385104
This is not what lambdas are for, and there is no syntax to do it (aside from hacking away the warning).
Just write a proper function template. Not everything has to be a lambda.
Upvotes: 5
Reputation: 302757
If you really don't need the argument, just wrap it in void
:
auto lambda = [](auto var) {
(void)var; // now we used it - more or less
decltype(var) x;
/* whatever else */
};
Upvotes: 10