c++11 std::declval 详解

函数模板

std::declval (c++11 only)


template<typename T>

  typename add_rvalue_reference<T>::type declval() noexcept;

功能描述:

 返回一个类型的右值引用,不管是否有没有默认构造函数或该类型不可以创建对象。(可以用于抽象基类);

参数:

返回值:

类型T的右值引用

例子:

// declval example
#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 << '
';
  return 0;
}

  

原文地址:https://www.cnblogs.com/chengyuanchun/p/5023296.html