decltype
cppreference.com
.
decltype ( )
|
(1) | ( C++11) | |||||||
decltype ( )
|
(2) | ( C++11) | |||||||
2)
T , , lvalue, decltype(x) decltype((x)) .
decltype , , , , -, , .
__cpp_decltype |
200707L |
(C++11) |
#include <iostream>
#include <type_traits>
struct A { double x; };
const A* a;
decltype(a->x) y; // y double ( )
decltype((a->x)) z = y; // z const double& ( lvalue)
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) //
// ,
// ++14
{
return t + u;
}
const int& getRef(const int* p) { return *p; }
static_assert(std::is_same_v<decltype(getRef), const int&(const int*)>);
auto getRefFwdBad(const int* p) { return getRef(p); }
static_assert(std::is_same_v<decltype(getRefFwdBad), int(const int*)>,
" auto .");
decltype(auto) getRefFwdGood(const int* p) { return getRef(p); }
static_assert(std::is_same_v<decltype(getRefFwdGood), const int&(const int*)>,
" decltype(auto) .");
// :
auto getRefFwdGood1(const int* p) -> decltype(getRef(p)) { return getRef(p); }
static_assert(std::is_same_v<decltype(getRefFwdGood1), const int&(const int*)>,
" decltype( return) .");
int main()
{
int i = 33;
decltype(i) j = i * 2;
static_assert(std::is_same_v<decltype(i), decltype(j)>);
assert(i == 33 && 66 == j);
auto f = [i](int a, int b) -> int { return a * b + i; };
auto h = [i](int a, int b) -> int { return a * b + i; };
static_assert(!std::is_same_v<decltype(f), decltype(h)>,
" - ");
decltype(f) g = f;
std::cout << f(3, 3) << ' ' << g(3, 3) << '\n';
}
:
42 42
auto (C++11)
|
, |
(C++11) |
( ) |
(C++11) |
, ( ) |
C typeof
| |