如何将模板参数限制为仅浮点类型

dig*_*evo 4 c++ templates c++20

有没有办法将模板参数限制T为特定类型或类别?

下面的代码有效,但我想让它更简单:

#include <iostream>
#include <type_traits>


template <typename T>
constexpr auto func( const T num ) -> T
{
    static_assert( std::is_floating_point_v<T>, "Floating point required." );

    return num * 123;
}

int main( )
{
    std::cout << func( 4345.9 ) << ' ' // should be ok
              << func( 3 ) << ' ' // should not compile
              << func( 55.0f ) << '\n'; // should be ok
}
Run Code Online (Sandbox Code Playgroud)

我想摆脱static_assert并写这样的东西:

template < std::is_floating_point_v<T> >
constexpr auto func( const T num ) -> T
{
    return num * 123;
}
Run Code Online (Sandbox Code Playgroud)

有什么建议么?来自type_traits概念的任何内容都会更好。

康桓瑋*_*康桓瑋 10

您可以使用std::floating_point概念来约束类型T

#include <concepts>

template<std::floating_point T>
constexpr auto func( const T num ) -> T {
  return num * 123;
}
Run Code Online (Sandbox Code Playgroud)

演示