c++ - void 类型的函数参数
问题描述
是否可以在不定义 的显式特化的情况下编译以下伪代码GetValue<void>
?
template <class Increment = void>
inline int GetValue(const Increment & inc = {})
{
if constexpr (std::is_same_v<Increment, void>)
{
return 25;
}
else
{
return 25 + inc;
}
}
int main()
{
std::cout << GetValue(1) << std::endl; //compiles
std::cout << GetValue() << std::endl; //does not compile
}
在这个伪代码中,我将一个值作为 GetValue 参数传递,通过该值增加 25 常量或指示“绝对没有”的某个值。而且还不清楚这个“绝对没有”是什么,以及如果一个类型的参数void
无法编译,如何表示它。
如果我定义一个假类型
struct Nothing {};
它可能看起来什么都没有,但不像“绝对没有”。
解决方案
不,您不能拥有类型为 的对象void
。但是,您不需要专业化。你所需要的只是一个重载:
int GetValue()
{
return 25;
}
template <class Increment>
int GetValue(const Increment& inc)
{
return GetValue() + inc;
}
您的另一个选择是将模板参数默认为以下内容void
:
template <class Increment = int>
int GetValue(const Increment& inc = {})
{
return 25 + inc;
}
然后一个GetValue()
调用实际上变成GetValue(0)
了 ,它也完成了这项工作。
推荐阅读
- php - 如何通过 WP CLI 取消 WP All Import?
- discord - 当事件发生在 Discord、OBS 更新中的浏览器源时,如何做到这一点?
- reactjs - How do I properly set up my useEffect so I don't receive a missing dependency warning?
- python - 如何在 Python (< 3.10) 中使用不同数量的参数注释相互依赖的函数参数和返回类型?
- javascript - 在 ReactJS 中实现简单的 Google oAuth
- typescript - Chart.js 无法在 Preact + Typescript 中更新 fontSize
- ruby - Gem::NameTuple credentials_manager, 1.0.0, ruby 更新 fastlane 时
- angularjs - 如何在单独的文件中使用 Ngmodel 的值来显示该值?
- c# - System.ArgumentNullException:值不能为空。(参数“连接字符串”)
- python - 将堆栈的 pop() 值保存到新变量中