繁体   English   中英

void 类型的函数参数

[英]A function parameter of type 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) ,它也完成了这项工作。

这是一个基于可变参数模板的想法:

template <typename ...INCREMENT>
int GetValue(const INCREMENT &...inc) {
    // this "if" is not actually needed for this example, but if you want
    // to discriminate between zero/non-zero number of parameters,
    // it can be done this way
    if constexpr (sizeof...(inc) == 0) {
        return 25;
    } else {
        return (25 + ... + inc);
        // or you can use this:
        // const auto &i = (inc, ...);
        // return 25 + i;
    }
}

int main() {
    std::cout<<GetValue(1)<<"\n";
    std::cout<<GetValue()<<"\n";
}

请注意,此解决方案允许使用任意数量的参数。 如果你必须有一个零或一个参数GetValue ,我认为你可以使用 SFINAE 只允许一个参数。

(例如,您可以使用std::enable_if_t<sizeof...(INCREMENT)<=1, int>作为函数的返回类型)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM