1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 // <functional> 10 11 // class function<R(ArgTypes...)> 12 13 // function(F); 14 15 #include <functional> 16 #include <cassert> 17 18 #include "test_macros.h" 19 #include "count_new.h" 20 21 class A 22 { 23 int data_[10]; 24 public: 25 static int count; 26 27 A() 28 { 29 ++count; 30 for (int i = 0; i < 10; ++i) 31 data_[i] = i; 32 } 33 34 A(const A&) {++count;} 35 36 ~A() {--count;} 37 38 int operator()(int i) const 39 { 40 for (int j = 0; j < 10; ++j) 41 i += data_[j]; 42 return i; 43 } 44 45 int foo(int) const {return 1;} 46 }; 47 48 int A::count = 0; 49 50 int g(int) {return 0;} 51 52 #if TEST_STD_VER >= 11 53 struct RValueCallable { 54 template <class ...Args> 55 void operator()(Args&&...) && {} 56 }; 57 struct LValueCallable { 58 template <class ...Args> 59 void operator()(Args&&...) & {} 60 }; 61 #endif 62 63 int main(int, char**) 64 { 65 globalMemCounter.reset(); 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 return 0; 117 } 118