c++ - 函数和类构造函数有什么区别?
问题描述
无法弄清楚下面的代码之间h1
有什么区别:h2
#include <utility>
template <class Func>
struct Holder
{
Holder(Func && func) : m_func(std::forward<Func>(func))
{
}
Func m_func;
};
template <class Func>
auto MakeHolder(Func && func)
{
return Holder<Func>(std::forward<Func>(func));
}
int main()
{
auto func = [](int val) {};
Holder h1 = MakeHolder(func);
Holder<decltype(func)> h2(func);
return 0;
}
为什么h1
编译,但h2
不编译?GCC的错误是
prog.cc:25 : 31 : error : cannot bind rvalue reference of type 'main()::<lambda(int)>&&' to lvalue of type 'main()::<lambda(int)>'
25 | Holder<decltype(func)> h2(func);
Func
函数模板参数中的decltype<func>
类型是否main()
不同?
解决方案
不同之处在于 Holder 类是用不同的类型实例化的Func
:
- 对于
h1
,是main()::<lambda(int)>&
- 对于
h2
,是main()::<lambda(int)>
你看,当你有一个类型为 T 的变量并使用它时,使用的类型与变量的类型不同:T&
而不是T
. 但在decltype()
语义上是不同的。
无论如何,您可以像这样编译代码:
#include <utility>
template <class Func>
struct Holder
{
Holder(Func func) : m_func(func) { }
Func m_func;
};
template <class Func>
auto MakeHolder(Func && func)
{
return Holder<Func>(std::forward<Func>(func));
}
int main()
{
auto func = [](int) {};
[[maybe_unused]] Holder h1 = MakeHolder(func);
[[maybe_unused]] Holder<decltype(func)> h2(func);
}
或者如果你真的必须 -std::move(func)
在初始化列表中使用。但是 - 我不确定我是否会保留一个Func
成员,因为它是任意Func
的(例如,当它是一个引用或指向可能会消失的临时对象的指针时。
推荐阅读
- shell - 在 shell 脚本中,我的文件是 .TXT 文件,其中包含名称。我想执行命令 echo $firstname 它打印姓氏
- javascript - 禁用从自动完成多个primeng中删除项目的选项
- c# - 为 AzureFunction 设置 Serilog
- sequelize.js - 在 Sequelize 中使用 afterCreate 钩子更新另一个表
- python - 如何从函数运行导入?
- javascript - 我需要帮助解决错误,未定义的对象会阻止代码运行
- azure-devops - Azure Devops 管道中的 IP 地址可以使用哪些数据类型的参数?
- spring - 如何将锁定设置为在上次更新后几分钟内不更新的记录
- unity3d - 在时间线中播放时音频有破裂的声音
- .net - 通过 .net wrapper 运行 ffmpeg 并将连续文本输出集成到程序中