编程语言
首页 > 编程语言> > c++11 decay/decltype/declval

c++11 decay/decltype/declval

作者:互联网

decay

std::decay对类型进行退化处理。
a. T为数组U或数组U引用,则type为U*.
b. T为函数时,则type为std::add_pointer::type.
c. 其它类型则移除cv限定符(const和volatile),则type为std::remove_cv<std::remove_reference::type>::type.

#include <type_traits>

typedef std::decay<int>::type A;           // int
typedef std::decay<int&>::type B;          // int
typedef std::decay<int&&>::type C;         // int
typedef std::decay<const int&>::type D;    // int
typedef std::decay<int[2]>::type E;        // int*
typedef std::decay<int(int)>::type F;      // int(*)(int)

typedef int X[3];

int main() {
  std::cout << std::boolalpha;
  std::cout << "typedefs of int:" << std::endl;
  std::cout << "A: " << std::is_same<int,A>::value << std::endl;
  std::cout << "B: " << std::is_same<int,B>::value << std::endl;
  std::cout << "C: " << std::is_same<int,C>::value << std::endl;
  std::cout << "D: " << std::is_same<int,D>::value << std::endl;
  std::cout << "E: " << std::is_same<int,E>::value << std::endl;
  std::cout << "F: " << std::is_same<int,F>::value << std::endl;

  return 0;
}

declval

std::declval 返回对象的右值引用,不管对象是否有构造函数,一般配合decltype使用。This function shall only be used in unevaluated operands (such as the operands of sizeof and decltype).T may be an incomplete type.
This is a helper function used to refer to members of a class in unevaluated operands ** , especially when either the constructor signature is unknown or when no objects of that type can be constructed (such as for abstract base classes).

#include <utility>      // std::declval
#include <iostream>     // std::cout

struct A {              // abstract class
  virtual int value() = 0;
};

class B : public A {    // class with specific constructor
  int val_;
public:
  B(int i,int j):val_(i*j){}
  int value() {return val_;}
};

int main() {
  decltype(std::declval<A>().value()) a;  // int a
  decltype(std::declval<B>().value()) b;  // int b
  decltype(B(0,0).value()) c;   // same as above (known constructor)
  a = b = B(10,2).value();
  std::cout << a << '\n';
  return 0;
}

decltype

delctype 可以在编译期内推导表达式所得值的类型。

template<typename T1, typename T2>    
void sum(T1 &t1, T2 &t2, decltype(t1 + t2) &s)  
{    
    s = t1 + t2;    
}  
  
template<typename T1, typename T2>    
auto sum(T1 &t1, T2 &t2) ->decltype(t1 + t2))  
{    
    return t1 + t2;    
}   
  
int hash(char*);  
map<string, decltype(hash(nullptr))> mm;  // 动态指定hash()返回类型,方便后续维护  

标签:11,std,decltype,declval,decay,int,value,type
来源: https://www.cnblogs.com/ultramanX/p/16201975.html