1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // This is a sandbox for modeling C++17 code generator.
18 // C++17 code generator: "flatc --cpp_std c++17".
19 // Warning:
20 // This is an experimental feature and could change at any time.
21 
22 #include "flatbuffers/flatbuffers.h"
23 #include "flatbuffers/flexbuffers.h"
24 #include "flatbuffers/idl.h"
25 #include "flatbuffers/minireflect.h"
26 #include "flatbuffers/registry.h"
27 #include "flatbuffers/util.h"
28 #include "test_assert.h"
29 
30 // Embed generated code into an isolated namespace.
31 namespace cpp17 {
32 #include "generated_cpp17/monster_test_generated.h"
33 }  // namespace cpp17
34 
35 namespace cpp11 {
36 #include "../monster_test_generated.h"
37 }  // namespace cpp11
38 
CreateTableByTypeTest()39 void CreateTableByTypeTest() {
40   flatbuffers::FlatBufferBuilder builder;
41 
42   // We will create an object of this type using only the type.
43   using type_to_create_t = cpp17::MyGame::Example::Stat;
44 
45   [&builder] {
46     auto id_str = builder.CreateString("my_id");
47     auto table = type_to_create_t::Traits::Create(builder, id_str, 42, 7);
48     // Be sure that the correct return type was inferred.
49     static_assert(
50         std::is_same_v<decltype(table), flatbuffers::Offset<type_to_create_t>>);
51     builder.Finish(table);
52   }();
53 
54   // Access it.
55   auto stat =
56       flatbuffers::GetRoot<type_to_create_t>(builder.GetBufferPointer());
57   TEST_EQ_STR(stat->id()->c_str(), "my_id");
58   TEST_EQ(stat->val(), 42);
59   TEST_EQ(stat->count(), 7);
60 }
61 
FlatBufferCpp17Tests()62 int FlatBufferCpp17Tests() {
63   CreateTableByTypeTest();
64   return 0;
65 }
66 
main(int,const char * [])67 int main(int /*argc*/, const char * /*argv*/[]) {
68   InitTestEngine();
69 
70   FlatBufferCpp17Tests();
71 
72   if (!testing_fails) {
73     TEST_OUTPUT_LINE("C++17: ALL TESTS PASSED");
74   } else {
75     TEST_OUTPUT_LINE("C++17: %d FAILED TESTS", testing_fails);
76   }
77   return CloseTestEngine();
78 }
79