1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
4 * Ceph - scalable distributed file system
6 * Copyright (C) 2017 Red Hat, Inc.
8 * Author: Casey Bodley <cbodley@redhat.com>
10 * This is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License version 2.1, as published by the Free Software
13 * Foundation. See file COPYING.
17 #include "common/backport14.h" // include first: tests that header is standalone
18 #include <gtest/gtest.h>
20 int int_func() { return 1; }
21 bool bool_func0() { return true; }
22 bool bool_func1(int a) { return true; }
23 bool bool_func2(const std::string& a, int b) { return true; }
25 // given a callable and argument list, test that the result of ceph::not_fn
26 // evaluates to false as both an lvalue and rvalue
27 template <typename F, typename ...Args>
28 void test_not(F&& fn, Args&&... args)
30 auto res = ceph::not_fn(std::forward<F>(fn));
32 EXPECT_FALSE(res(std::forward<Args>(args)...));
34 // note: this forwards args twice, but it's okay if none are rvalues
35 EXPECT_FALSE(std::move(res)(std::forward<Args>(args)...));
38 TEST(Backport14, not_fn)
44 test_not(&bool_func0);
45 test_not(bool_func1, 5);
46 test_not(bool_func2, "foo", 5);
49 auto int_lambda = [] { return 1; };
50 auto bool_lambda0 = [] { return true; };
51 auto bool_lambda1 = [] (int a) { return true; };
52 auto bool_lambda2 = [] (const std::string& a, int b) { return true; };
55 test_not(bool_lambda0);
56 test_not(bool_lambda1, 5);
57 test_not(bool_lambda2, "foo", 5);
61 int operator()() { return 1; }
63 test_not(int_functor{});
66 bool operator()() { return true; }
67 bool operator()(int a) { return true; }
68 bool operator()(const std::string& a, int b) { return true; }
71 test_not(bool_functor{});
72 test_not(bool_functor{}, 5);
73 test_not(bool_functor{}, "foo", 5);
75 // lvalue-only overload
76 struct lvalue_only_functor {
77 bool operator()() & { return true; } // no overload for rvalue
79 auto lvalue_result = ceph::not_fn(lvalue_only_functor{});
80 EXPECT_FALSE(lvalue_result());
81 // should not compile:
82 // EXPECT_FALSE(std::move(lvalue_result)());
84 // rvalue-only overload
85 struct rvalue_only_functor {
86 bool operator()() && { return true; } // no overload for lvalue
88 EXPECT_FALSE(ceph::not_fn(rvalue_only_functor{})());
89 auto lvalue_functor = rvalue_only_functor{};
90 EXPECT_FALSE(ceph::not_fn(lvalue_functor)()); // lvalue functor, rvalue result
91 // should not compile:
92 // auto lvalue_result2 = ceph::not_fn(rvalue_only_functor{});
93 // EXPECT_FALSE(lvalue_result2());