我想为只从第二次迭代开始运行的 for 循环创建一个辅助函数,因为我有很多具有以下模式的代码:
firstItem = true;
for (unsigned i = 0; i < 5; ++i)
{
firstItem ? firstItem = false : std::cout << ",\n";
std::cout << i;
}
我开始为此考虑一个辅助函数,然后想出了这个解决方案:
template <typename T>
void fromSecondIter(T fn)
{
static bool firstItem = true; // because of this it works with unique types only
if (firstItem)
firstItem = false;
else
fn();
}
我的问题是,当 T 是唯一类型时,此解决方案可以正常工作。所以传递一个 lambda 是可以的,但是传递一个函数会默默地导致错误。然后我将该 fn 参数包装到一个 lambda 中,但令人惊讶的是它没有帮助;
这是一个完整的例子:
#include <type_traits>
#include <iostream>
#include <functional>
template <typename T>
void fromSecondIter(T fn)
{
static bool firstItem = true;
if (firstItem)
firstItem = false;
else
fn();
}
template <typename T>
void iterTest(T fn)
{
std::cout << "Numbers: ";
for (unsigned i = 0; i < 5; ++i)
{
fromSecondIter([&fn](){ fn(); }); // bad, why lambda is not unique here???
std::cout << i;
}
std::cout << std::endl;
}
void foo()
{
std::cout << ", ";
}
void test()
{
iterTest([](){ std::cout << ", "; }); // ok, lambda is unique
iterTest([](){ std::cout << ", "; }); // ok, lambda is unique
iterTest(foo); // ok
iterTest(foo); // bad
}
int main()
{
test();
return 0;
}
这打印:
Numbers: 0, 1, 2, 3, 4
Numbers: 0, 1, 2, 3, 4
Numbers: 0, 1, 2, 3, 4
Numbers: , 0, 1, 2, 3, 4
最佳答案
Lambda 表达式创建唯一类型,但这并不意味着每次执行通过代码中的一个时都会创建一个新的唯一类型:
int main() {
for (int i=0; i<3; ++i) {
[] { std::cout << "Hello, World\n"; }();
}
}
上面的 for 循环创建了三个相同类型的对象。
在您的代码中,您有一个模板函数 iterTest
,它包含一个 lambda 表达式。这意味着对于 iterTest
的每个实例化,lambda 表达式都将具有唯一的类型。但是,如果您运行 iterTest
的相同实例化,则 lambda 表达式每次都具有相同的类型。这就是这里发生的事情。
作为示例,这里有一个解决方法,对您的示例代码进行了最少的更改:
template <typename T>
void iterTest(T fn)
{
std::cout << "Numbers: ";
for (unsigned i = 0; i < 5; ++i)
{
fromSecondIter(fn);
std::cout << i;
}
std::cout << std::endl;
}
void test()
{
iterTest([](){ std::cout << ", "; }); // ok, lambda is unique
iterTest([](){ std::cout << ", "; }); // ok, lambda is unique
iterTest([]{foo();}); // ok
iterTest([]{foo();}); // also ok
}
fromSecondIter
的当前实现将创建一个静态变量,该变量从创建时一直持续到程序结束,并且从程序开始就为它保留内存。这不是很大的成本,但是有更好的方法;创建一个具有 bool 成员变量的对象,以及具有必要逻辑的成员函数(例如,operator()
)。
#include <iostream>
struct skipper {
bool first = true;
template<typename Fn>
void operator() (Fn &&fn) {
if (first)
first = false;
else
fn();
}
};
int main()
{
skipper skip_first;
for (int i=0; i<10; ++i) {
skip_first([]{ std::cout << ", "; });
std::cout << i;
}
}
这意味着使用它需要两行而不是一行,但现在您可以控制范围。
关于c++ - 如何为 lambda 创建唯一类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19300557/