函数模板通用引用错误

The*_*der 2 c++ templates c++20

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

当我写下这个:

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 ? -(number) : number;
}

const double num3 { -12.5 };

std::cout << absolute(num3) << std::endl;   // Compiler warns: no matching overloaded function found
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么吗?

0xb*_*ann 5

从您的概念中删除cv限定符和引用也允许使用 const 和引用:is_numberaddabsolute

template <typename Type>
concept is_number = std::integral<std::remove_cvref_t<Type>> || 
                    std::floating_point<std::remove_cvref_t<Type>>;
Run Code Online (Sandbox Code Playgroud)