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.hpp" 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 assert(globalMemCounter.checkOutstandingNewEq(0)); 66 { 67 std::function<int(int)> f = A(); 68 assert(A::count == 1); 69 assert(globalMemCounter.checkOutstandingNewEq(1)); 70 assert(f.target<A>()); 71 assert(f.target<int(*)(int)>() == 0); 72 } 73 assert(A::count == 0); 74 assert(globalMemCounter.checkOutstandingNewEq(0)); 75 { 76 std::function<int(int)> f = g; 77 assert(globalMemCounter.checkOutstandingNewEq(0)); 78 assert(f.target<int(*)(int)>()); 79 assert(f.target<A>() == 0); 80 } 81 assert(globalMemCounter.checkOutstandingNewEq(0)); 82 { 83 std::function<int(int)> f = (int (*)(int))0; 84 assert(!f); 85 assert(globalMemCounter.checkOutstandingNewEq(0)); 86 assert(f.target<int(*)(int)>() == 0); 87 assert(f.target<A>() == 0); 88 } 89 { 90 std::function<int(const A*, int)> f = &A::foo; 91 assert(f); 92 assert(globalMemCounter.checkOutstandingNewEq(0)); 93 assert(f.target<int (A::*)(int) const>() != 0); 94 } 95 { 96 std::function<void(int)> f(&g); 97 assert(f); 98 assert(f.target<int(*)(int)>() != 0); 99 f(1); 100 } 101 { 102 std::function <void()> f(static_cast<void (*)()>(0)); 103 assert(!f); 104 } 105 #if TEST_STD_VER >= 11 106 { 107 using Fn = std::function<void(int, int, int)>; 108 static_assert(std::is_constructible<Fn, LValueCallable&>::value, ""); 109 static_assert(std::is_constructible<Fn, LValueCallable>::value, ""); 110 static_assert(!std::is_constructible<Fn, RValueCallable&>::value, ""); 111 static_assert(!std::is_constructible<Fn, RValueCallable>::value, ""); 112 } 113 #endif 114 115 return 0; 116 } 117