首页 > 解决方案 > 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 {};

它可能看起来什么都没有,但不像“绝对没有”。

标签: c++c++17

解决方案


不,您不能拥有类型为 的对象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)了 ,它也完成了这项工作。


推荐阅读