有沒有辦法將模板引數限制為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
}
我想擺脫static_assert并寫這樣的東西:
template < std::is_floating_point_v<T> >
constexpr auto func( const T num ) -> T
{
return num * 123;
}
有什么建議?type_traits或概念中的任何內容都會更好。
uj5u.com熱心網友回復:
您可以使用std::floating_point概念來約束型別T:
#include <concepts>
template<std::floating_point T>
constexpr auto func( const T num ) -> T {
return num * 123;
}
演示
uj5u.com熱心網友回復:
下面的代碼有效,但我想讓它更簡單:
您可以將縮寫函式模板和壓縮約束函式模板定義的std::floating_point概念結合起來:
constexpr auto func(std::floating_point auto num) {
return num * 123;
}
請注意,這不包括T在原始方法中明確指定的尾隨回傳型別,但對于當前定義,推導的回傳型別將是decltype(num),它是floator double(或 impl-defined long double)。正如@Barry 在下面的評論中指出的那樣,如果您需要一個尾隨回傳型別,例如具有 ref 和 cv 限定的函式引數的多載,那么縮寫模板的簡潔性增益會因復雜的尾隨回傳的額外成本而丟失型別。
// Contrived example: but if this was the design intent,
// then no: skip the abbreviated function template approach.
constexpr auto func(const std::floating_point auto& num)
-> std::remove_cvref_t<decltype(num)> { /* ... */ }
// ... and prefer
template<std::floating_point T>
constexpr auto func(const T& num) -> T { /* ... */ }
// ... or (preferential)
template<std::floating_point T>
constexpr T func(const T& num) { /* ... */ }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/415738.html
標籤:
上一篇:實作模板專用功能
