gpt4 book ai didi

c++ - 仅为基本数据类型制作模板

转载 作者:行者123 更新时间:2023-12-02 19:37:04 25 4
gpt4 key购买 nike

我们如何使模板只接受基本数据类型。

template <typename T> 
void GetMaxValue( T& x )
{
//... Finds max Value
}

在上面的函数中GetMaxValue我们能够传递任何值而不会出现任何错误。

但是 std 函数 std::numeric_limits<T>::max()已经处理了。例如:

auto max = std::numeric_limits< std::map<int,int> >::max();

会报错error C2440: '<function-style-cast>' : cannot convert from 'int' to 'std::map<_Kty,_Ty>'

最佳答案

在 C++20 中存在约束:

#include <type_traits>
template <class T>
requires std::is_arithmetic_v<T>
void GetMaxValue( T& x )
{
//... Finds max Value
}

用法:

int a = 0;
GetMaxValue(a); // fine

std::vector<int> b;
GetMaxValue(b); // compiler error

Demo


使用std::enable_if,否则:

template <class T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0> 
void GetMaxValue( T& x )
{
//... Finds max Value
}

Demo 2


预约束的错误消息更难阅读:

error: no matching function for call to 'GetMaxValue(std::vector<int>&)'
| GetMaxValue(b); // compiler error
| ^
Note: candidate: 'template<class T, typename std::enable_if<is_arithmetic_v<T>, int>::type <anonymous> > void GetMaxValue(T&)'
| void GetMaxValue( T& x )
| ^~~~~~~~~~~
note: template argument deduction/substitution failed:
error: no type named 'type' in 'struct std::enable_if<false, int>'
| template <class T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0>
| ^
In instantiation of 'void GetMaxValue(T&) [with T = int; typename std::enable_if<is_arithmetic_v<T>, int>::type <anonymous> = 0]'

对比

error: cannot call function 'void GetMaxValue(T&) [with T = std::vector<int>]'
| GetMaxValue(b); // compiler error
| ^
note: constraints not satisfied
In function 'void GetMaxValue(T&) [with T = std::vector<int>]':
required by the constraints of 'template<class T> requires is_arithmetic_v<T> void GetMaxValue(T&)'
note: the expression 'is_arithmetic_v<T>' evaluated to 'false'
| requires std::is_arithmetic_v<T>
| ~~~~~^~~~~~~~~~~~~~~~~~

关于c++ - 仅为基本数据类型制作模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58643348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com