小编The*_*der的帖子

函数模板通用引用错误

我正在尝试编写一个函数模板,该模板采用通用引用作为参数,以便它可以接受左值引用和右值引用。

当我写下这个:

template <typename Type>
concept is_number = std::integral<Type> || std::floating_point<Type>;

template <typename Type1, typename Type2>
    requires is_number<Type1> && is_number<Type2>
[[nodiscard]] inline auto add(Type1&& num1, Type2&& num2) noexcept
{
    return num1 + num2;
}

const std::int64_t num1 { 50 };
const double num2 { 30.6 };

std::cout << add(num1, num2) << std::endl;
Run Code Online (Sandbox Code Playgroud)

该代码按预期工作。add() 函数模板成功推导为

[[nodiscard]] inline double add(const std::int64_t& num1, const double& num2);
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试这段代码时:

template <typename Type>
    requires is_number<Type>
[[nodiscard]] inline auto absolute(Type&& number) noexcept
{
    return number < 0 …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++20

2
推荐指数
1
解决办法
70
查看次数

标签 统计

c++ ×1

c++20 ×1

templates ×1