使模板仅适用于基本数据类型

Kir*_*lak 2 c++ templates c++11

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

template <typename T> 
void GetMaxValue( T& x ) 
{ 
//... Finds max Value
} 
Run Code Online (Sandbox Code Playgroud)

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

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

auto max = std::numeric_limits< std::map<int,int> >::max();
Run Code Online (Sandbox Code Playgroud)

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

And*_*dyG 5

在C ++ 20中有约束:

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

用法:

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

std::vector<int> b;
GetMaxValue(b); // compiler error
Run Code Online (Sandbox Code Playgroud)

演示版


随着std::enable_if否则:

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

演示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]'
Run Code Online (Sandbox Code Playgroud)

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>
  |          ~~~~~^~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)