【发布时间】:2018-08-28 05:52:12
【问题描述】:
假设您有一个带有 std::tuple 的可变参数类,可以使用 args + 1 个新 arg 移动构造。当使用std::apply() 和原始花括号构造函数构造时,该构造函数不会返回右值。这意味着类不是移动构造的。下面举例说明。
#include <cstdio>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <vector>
template <class... Args>
struct icecream {
icecream() = default;
template <class... MoreArgs>
icecream(icecream<MoreArgs...>&& ice) {
std::apply(
[this](auto&&... ds) {
data = { std::move(ds)..., {} };
},
std::move(ice.data));
}
// This works :
// template <class... MoreArgs>
// icecream(icecream<MoreArgs...>&& ice) {
// std::apply(
// [this](auto&&... ds) {
// data = { std::move(ds)...,
// std::move(std::vector<double>{}) };
// },
// std::move(ice.data));
// }
std::tuple<std::vector<Args>...> data{};
};
int main(int, char**) {
icecream<int> miam;
std::get<0>(miam.data).push_back(1);
std::get<0>(miam.data).push_back(2);
icecream<int, double> cherry_garcia{ std::move(miam) };
printf("miam : \n");
for (const auto& x : std::get<0>(miam.data)) {
printf("%d\n", x);
}
printf("\ncherry_garcia : \n");
for (const auto& x : std::get<0>(cherry_garcia.data)) {
printf("%d\n", x);
}
return 0;
}
输出是:
miam :
1
2
cherry_garcia :
1
2
这个例子有点笨拙,但说明了这一点。在第一个移动构造函数中,使用{} 并构造元组复制构造。如果您使用硬编码的std::move() 取消注释第二个构造函数,那么它可以工作。
我在 VS 最新版、clang 最新版和 gcc 最新版上进行测试。都有相同的结果。 (魔杖盒:https://wandbox.org/permlink/IQqqlLcmeyOzsJHC)
所以问题是,为什么不返回一个右值呢?我显然错过了 curl 构造函数的一些东西。这可能与可变参数无关,但我认为我不妨展示真实的场景。
【问题讨论】:
-
你期望什么输出,但你没有得到?
-
&& 在模板的参数中不是右值引用,它是一个“通用引用”。您的意思是将构造函数作为模板吗?
标签: c++ templates c++17 variadic-templates generic-lambda