是否可以在不定义 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)
,它也可以完成这项工作。关于c++ - void 类型的函数参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60579619/