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

时间:2019-10-31 12:27:16

标签: c++ c++11 templates

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

// In the job:
public function handle() {
   // check if there is available worker

   // start job in worker

   while ($job->status != 'completed') {
      sleep(3);   
   }
}

在上述功能template <typename T> void GetMaxValue( T& x ) { //... Finds max Value } 中,我们可以传递 任何 值,而不会出现任何错误。

但是std函数GetMaxValue已经处理了它。 例如:

std::numeric_limits<T>::max()

将给出错误auto max = std::numeric_limits< std::map<int,int> >::max();

1 个答案:

答案 0 :(得分:5)

在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]'

vs

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>
  |          ~~~~~^~~~~~~~~~~~~~~~~~
相关问题