1 //===----------------------------------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 // <functional>
11
12 // class function<R(ArgTypes...)>
13
14 // function(F);
15
16 #include <functional>
17 #include <cassert>
18
19 #include "test_macros.h"
20 #include "count_new.hpp"
21
22 class A
23 {
24 int data_[10];
25 public:
26 static int count;
27
A()28 A()
29 {
30 ++count;
31 for (int i = 0; i < 10; ++i)
32 data_[i] = i;
33 }
34
A(const A &)35 A(const A&) {++count;}
36
~A()37 ~A() {--count;}
38
operator ()(int i) const39 int operator()(int i) const
40 {
41 for (int j = 0; j < 10; ++j)
42 i += data_[j];
43 return i;
44 }
45
foo(int) const46 int foo(int) const {return 1;}
47 };
48
49 int A::count = 0;
50
g(int)51 int g(int) {return 0;}
52
53 #if TEST_STD_VER >= 11
54 struct RValueCallable {
55 template <class ...Args>
operator ()RValueCallable56 void operator()(Args&&...) && {}
57 };
58 struct LValueCallable {
59 template <class ...Args>
operator ()LValueCallable60 void operator()(Args&&...) & {}
61 };
62 #endif
63
main()64 int main()
65 {
66 assert(globalMemCounter.checkOutstandingNewEq(0));
67 {
68 std::function<int(int)> f = A();
69 assert(A::count == 1);
70 assert(globalMemCounter.checkOutstandingNewEq(1));
71 assert(f.target<A>());
72 assert(f.target<int(*)(int)>() == 0);
73 }
74 assert(A::count == 0);
75 assert(globalMemCounter.checkOutstandingNewEq(0));
76 {
77 std::function<int(int)> f = g;
78 assert(globalMemCounter.checkOutstandingNewEq(0));
79 assert(f.target<int(*)(int)>());
80 assert(f.target<A>() == 0);
81 }
82 assert(globalMemCounter.checkOutstandingNewEq(0));
83 {
84 std::function<int(int)> f = (int (*)(int))0;
85 assert(!f);
86 assert(globalMemCounter.checkOutstandingNewEq(0));
87 assert(f.target<int(*)(int)>() == 0);
88 assert(f.target<A>() == 0);
89 }
90 {
91 std::function<int(const A*, int)> f = &A::foo;
92 assert(f);
93 assert(globalMemCounter.checkOutstandingNewEq(0));
94 assert(f.target<int (A::*)(int) const>() != 0);
95 }
96 {
97 std::function<void(int)> f(&g);
98 assert(f);
99 assert(f.target<int(*)(int)>() != 0);
100 f(1);
101 }
102 {
103 std::function <void()> f(static_cast<void (*)()>(0));
104 assert(!f);
105 }
106 #if TEST_STD_VER >= 11
107 {
108 using Fn = std::function<void(int, int, int)>;
109 static_assert(std::is_constructible<Fn, LValueCallable&>::value, "");
110 static_assert(std::is_constructible<Fn, LValueCallable>::value, "");
111 static_assert(!std::is_constructible<Fn, RValueCallable&>::value, "");
112 static_assert(!std::is_constructible<Fn, RValueCallable>::value, "");
113 }
114 #endif
115 }
116