首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >仅为基本数据类型制作模板

仅为基本数据类型制作模板
EN

Stack Overflow用户
提问于 2019-10-31 12:27:16
回答 1查看 120关注 0票数 2

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

代码语言:javascript
复制
template <typename T> 
void GetMaxValue( T& x ) 
{ 
//... Finds max Value
} 

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

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

代码语言:javascript
复制
auto max = std::numeric_limits< std::map<int,int> >::max();

会给出一个错误error C2440: '<function-style-cast>' : cannot convert from 'int' to 'std::map<_Kty,_Ty>'

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-31 12:37:55

具有C++20中的约束:

代码语言:javascript
复制
#include <type_traits>
template <class T> 
requires std::is_arithmetic_v<T>
void GetMaxValue( T& x ) 
{ 
//... Finds max Value
}

用法:

代码语言:javascript
复制
int a = 0;
GetMaxValue(a); // fine

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

演示

如果使用std::enable_if,则为:

代码语言:javascript
复制
template <class T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0> 
void GetMaxValue( T& x ) 
{ 
//... Finds max Value
}

演示2

预约束前的错误消息很难读懂:

代码语言:javascript
复制
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]'

vs

代码语言:javascript
复制
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>
  |          ~~~~~^~~~~~~~~~~~~~~~~~
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58643348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档