我有C++代码包装任意lambda并返回lambda的结果.
template <typename F>
auto wrapAndRun(F fn) -> decltype(F()) {
// foo();
auto result = fn();
// bar();
return result;
}
Run Code Online (Sandbox Code Playgroud)
这有效,除非Freturn void(error: variable has incomplete type 'void').我想用a ScopeGuard来运行bar,但我不想bar在fn投掷时运行.有任何想法吗?
我正在尝试使用boost :: to_lower_copy和std :: transform来小写一堆字符串.如下所示,变体1,使用lamdba工作; 变体2也可以证明这是编译器选择的正确模板重载.但lambda是愚蠢的 - 它只是将单个参数转发到boost :: to_lower_copy.但Variant 3,直接使用函数模板不会编译,即使我实例化它.我错过了什么?
我有使用libstdc ++ - 4.8.1-1.fc19.i686和boost-1.53.0-14.fc19.i686的clang版本3.3(标签/ RELEASE_33/rc3).
vector<string> strings = {"Foo", "Bar"};
vector<string> lower_cased_strings;
transform(
strings.begin(),
strings.end(),
inserter(lower_cased_strings, lower_cased_strings.end()),
// Variant 1
// [](const string &word) {
// return boost::to_lower_copy(word);
// }
// Variant 2
// [](const string &word) {
// return boost::to_lower_copy<string>(word);
// }
// Variant 3
boost::to_lower_copy<string>
);
> clang++ -std=c++11 lowercase.cxx
In file included from lowercase.cxx:3:
In file included from /usr/include/boost/algorithm/string.hpp:18:
In file included from /usr/include/boost/algorithm/string/std_containers_traits.hpp:23:
In file …Run Code Online (Sandbox Code Playgroud) 我使用的库有很多类型,所有类型都来自相同的2个接口:
class Huey : public IDuck, public ICartoonCharacter
{
...
};
class Dewey : public IDuck, public ICartoonCharacter
{
...
};
class Louie : public IDuck, public ICartoonCharacter
{
...
};
Run Code Online (Sandbox Code Playgroud)
我想将所有上述类型的对象存储在包装类中,并将该包装类的对象粘贴到容器中.当然,我应该能够从我的包装类中调用属于这两个接口的方法.
我有什么选择?我能想到
IDuck *s 存储在我的包装器中,并将dynamic_cast-ing存储到ICartoonCharacter,或boost::any同时使我的包装器成为一个类模板,用几个static_asserts来确保模板参数继承自IDuck和ICartoonCharacter.但两种选择都没有特别吸引人.有任何想法吗?
两个接口,多个继承组合成一个容器?是一个相关的问题,但詹姆斯坎泽的答案对我不起作用,因为我不能改变3个班级.
编辑:不要经常使用多重继承,忘记了语法.现在public从两个接口继承.
编辑:现在使用dynamic_cast而不是static_cast(这将无法工作).
编辑:我发现Mike Seymour和Matthieu M的答案都很有希望.一旦我编码完毕,我会接受他们的一个答案.谢谢!
我有一个while循环,我想用std/boost算法取代(主要是为了我的学习,沿着Sean Parent的无原始循环格言).
std::queue q;
while (! q.empty()) {
auto front = q.front();
q.pop();
do_stuff_with_front();
potentially_insert_more_into_q();
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我有条件地将更多元素排入循环中; 想想迷宫遍历.什么std/boost算法可能适合这个?