summaryrefslogtreecommitdiff
path: root/compiler/cpp/src/thrift/generate/t_cpp_generator.cc
blob: c10d399373eedd403224fb1a513f6ee4ce119e0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 * Contains some contributions under the Thrift Software License.
 * Please see doc/old-thrift-license.txt in the Thrift distribution for
 * details.
 */

#include <cassert>

#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <vector>

#include <sys/stat.h>

#include "thrift/platform.h"
#include "thrift/generate/t_oop_generator.h"

using std::map;
using std::ofstream;
using std::ostream;
using std::string;
using std::vector;

static const string endl = "\n"; // avoid ostream << std::endl flushes

/**
 * C++ code generator. This is legitimacy incarnate.
 *
 */
class t_cpp_generator : public t_oop_generator {
public:
  t_cpp_generator(t_program* program,
                  const std::map<std::string, std::string>& parsed_options,
                  const std::string& option_string)
    : t_oop_generator(program) {
    (void)option_string;
    std::map<std::string, std::string>::const_iterator iter;


    gen_pure_enums_ = false;
    use_include_prefix_ = false;
    gen_cob_style_ = false;
    gen_no_client_completion_ = false;
    gen_no_default_operators_ = false;
    gen_templates_ = false;
    gen_templates_only_ = false;
    gen_moveable_ = false;
    gen_no_ostream_operators_ = false;
    gen_no_skeleton_ = false;
    has_members_ = false;

    for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) {
      if( iter->first.compare("pure_enums") == 0) {
        gen_pure_enums_ = true;
      } else if( iter->first.compare("include_prefix") == 0) {
        use_include_prefix_ = true;
      } else if( iter->first.compare("cob_style") == 0) {
        gen_cob_style_ = true;
      } else if( iter->first.compare("no_client_completion") == 0) {
        gen_no_client_completion_ = true;
      } else if( iter->first.compare("no_default_operators") == 0) {
        gen_no_default_operators_ = true;
      } else if( iter->first.compare("templates") == 0) {
        gen_templates_ = true;
        gen_templates_only_ = (iter->second == "only");
      } else if( iter->first.compare("moveable_types") == 0) {
        gen_moveable_ = true;
      } else if ( iter->first.compare("no_ostream_operators") == 0) {
        gen_no_ostream_operators_ = true;
      } else if ( iter->first.compare("no_skeleton") == 0) {
        gen_no_skeleton_ = true;
      } else {
        throw "unknown option cpp:" + iter->first;
      }
    }

    out_dir_base_ = "gen-cpp";
  }

  /**
   * Init and close methods
   */

  void init_generator() override;
  void close_generator() override;

  void generate_consts(std::vector<t_const*> consts) override;

  /**
   * Program-level generation functions
   */

  void generate_typedef(t_typedef* ttypedef) override;
  void generate_enum(t_enum* tenum) override;
  void generate_enum_ostream_operator_decl(std::ostream& out, t_enum* tenum);
  void generate_enum_ostream_operator(std::ostream& out, t_enum* tenum);
  void generate_enum_to_string_helper_function_decl(std::ostream& out, t_enum* tenum);
  void generate_enum_to_string_helper_function(std::ostream& out, t_enum* tenum);
  void generate_forward_declaration(t_struct* tstruct) override;
  void generate_struct(t_struct* tstruct) override { generate_cpp_struct(tstruct, false); }
  void generate_xception(t_struct* txception) override { generate_cpp_struct(txception, true); }
  void generate_cpp_struct(t_struct* tstruct, bool is_exception);

  void generate_service(t_service* tservice) override;

  void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value);
  std::string render_const_value(std::ostream& out,
                                 std::string name,
                                 t_type* type,
                                 t_const_value* value);

  void generate_struct_declaration(std::ostream& out,
                                   t_struct* tstruct,
                                   bool is_exception = false,
                                   bool pointers = false,
                                   bool read = true,
                                   bool write = true,
                                   bool swap = false,
                                   bool is_user_struct = false);
  void generate_struct_definition(std::ostream& out,
                                  std::ostream& force_cpp_out,
                                  t_struct* tstruct,
                                  bool setters = true,
                                  bool is_user_struct = false);
  void generate_copy_constructor(std::ostream& out, t_struct* tstruct, bool is_exception);
  void generate_move_constructor(std::ostream& out, t_struct* tstruct, bool is_exception);
  void generate_constructor_helper(std::ostream& out,
                                   t_struct* tstruct,
                                   bool is_excpetion,
                                   bool is_move);
  void generate_assignment_operator(std::ostream& out, t_struct* tstruct);
  void generate_move_assignment_operator(std::ostream& out, t_struct* tstruct);
  void generate_assignment_helper(std::ostream& out, t_struct* tstruct, bool is_move);
  void generate_struct_reader(std::ostream& out, t_struct* tstruct, bool pointers = false);
  void generate_struct_writer(std::ostream& out, t_struct* tstruct, bool pointers = false);
  void generate_struct_result_writer(std::ostream& out, t_struct* tstruct, bool pointers = false);
  void generate_struct_swap(std::ostream& out, t_struct* tstruct);
  void generate_struct_print_method(std::ostream& out, t_struct* tstruct);
  void generate_exception_what_method(std::ostream& out, t_struct* tstruct);

  /**
   * Service-level generation functions
   */

  void generate_service_interface(t_service* tservice, string style);
  void generate_service_interface_factory(t_service* tservice, string style);
  void generate_service_null(t_service* tservice, string style);
  void generate_service_multiface(t_service* tservice);
  void generate_service_helpers(t_service* tservice);
  void generate_service_client(t_service* tservice, string style);
  void generate_service_processor(t_service* tservice, string style);
  void generate_service_skeleton(t_service* tservice);
  void generate_process_function(t_service* tservice,
                                 t_function* tfunction,
                                 string style,
                                 bool specialized = false);
  void generate_function_helpers(t_service* tservice, t_function* tfunction);
  void generate_service_async_skeleton(t_service* tservice);

  /**
   * Serialization constructs
   */

  void generate_deserialize_field(std::ostream& out,
                                  t_field* tfield,
                                  std::string prefix = "",
                                  std::string suffix = "");

  void generate_deserialize_struct(std::ostream& out,
                                   t_struct* tstruct,
                                   std::string prefix = "",
                                   bool pointer = false);

  void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = "");

  void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = "");

  void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = "");

  void generate_deserialize_list_element(std::ostream& out,
                                         t_list* tlist,
                                         std::string prefix,
                                         bool push_back,
                                         std::string index);

  void generate_serialize_field(std::ostream& out,
                                t_field* tfield,
                                std::string prefix = "",
                                std::string suffix = "");

  void generate_serialize_struct(std::ostream& out,
                                 t_struct* tstruct,
                                 std::string prefix = "",
                                 bool pointer = false);

  void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = "");

  void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter);

  void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter);

  void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter);

  void generate_function_call(ostream& out,
                              t_function* tfunction,
                              string target,
                              string iface,
                              string arg_prefix);
  /*
   * Helper rendering functions
   */

  std::string namespace_prefix(std::string ns);
  std::string namespace_open(std::string ns);
  std::string namespace_close(std::string ns);
  std::string type_name(t_type* ttype, bool in_typedef = false, bool arg = false);
  std::string base_type_name(t_base_type::t_base tbase);
  std::string declare_field(t_field* tfield,
                            bool init = false,
                            bool pointer = false,
                            bool constant = false,
                            bool reference = false);
  std::string function_signature(t_function* tfunction,
                                 std::string style,
                                 std::string prefix = "",
                                 bool name_params = true);
  std::string cob_function_signature(t_function* tfunction,
                                     std::string prefix = "",
                                     bool name_params = true);
  std::string argument_list(t_struct* tstruct, bool name_params = true, bool start_comma = false);
  std::string type_to_enum(t_type* ttype);

  void generate_enum_constant_list(std::ostream& f,
                                   const vector<t_enum_value*>& constants,
                                   const char* prefix,
                                   const char* suffix,
                                   bool include_values);

  void generate_struct_ostream_operator_decl(std::ostream& f, t_struct* tstruct);
  void generate_struct_ostream_operator(std::ostream& f, t_struct* tstruct);
  void generate_struct_print_method_decl(std::ostream& f, t_struct* tstruct);
  void generate_exception_what_method_decl(std::ostream& f,
                                           t_struct* tstruct,
                                           bool external = false);

  bool is_reference(t_field* tfield) { return tfield->get_reference(); }

  bool is_complex_type(t_type* ttype) {
    ttype = get_true_type(ttype);

    return ttype->is_container() || ttype->is_struct() || ttype->is_xception()
           || (ttype->is_base_type()
               && (((t_base_type*)ttype)->get_base() == t_base_type::TYPE_STRING));
  }

  void set_use_include_prefix(bool use_include_prefix) { use_include_prefix_ = use_include_prefix; }

  /**
   * The compiler option "no_thrift_ostream_impl" can be used to prevent
   * the compiler from emitting implementations for operator <<.  In this
   * case the consuming application must provide any needed to build.
   *
   * To disable this on a per structure bases, one can alternatively set
   * the annotation "cpp.customostream" to prevent thrift from emitting an
   * operator << (std::ostream&).
   *
   * See AnnotationTest for validation of this annotation feature.
   */
  bool has_custom_ostream(t_type* ttype) const {
    return (gen_no_ostream_operators_) ||
           (ttype->annotations_.find("cpp.customostream") != ttype->annotations_.end());
  }

  /** 
   * Determine if all fields of t_struct's storage do not throw
   * Move/Copy Constructors and Assignments applicable for 'noexcept'
   * Move defaults to 'noexcept'
   */
  bool is_struct_storage_not_throwing(t_struct* tstruct) const;

private:
  /**
   * Returns the include prefix to use for a file generated by program, or the
   * empty string if no include prefix should be used.
   */
  std::string get_include_prefix(const t_program& program) const;

  /**
   * Returns the legal program name to use for a file generated by program, if the
   * program name contains dots then replace it with underscores, otherwise return the 
   * original program name.
   */
  std::string get_legal_program_name(std::string program_name);

  /**
   * True if we should generate pure enums for Thrift enums, instead of wrapper classes.
   */
  bool gen_pure_enums_;

  /**
   * True if we should generate templatized reader/writer methods.
   */
  bool gen_templates_;

  /**
   * True iff we should generate process function pointers for only templatized
   * reader/writer methods.
   */
  bool gen_templates_only_;

  /**
   * True if we should generate move constructors & assignment operators.
   */
  bool gen_moveable_;

  /**
   * True if we should generate ostream definitions
   */
  bool gen_no_ostream_operators_;

  /**
   * True iff we should use a path prefix in our #include statements for other
   * thrift-generated header files.
   */
  bool use_include_prefix_;

  /**
   * True if we should generate "Continuation OBject"-style classes as well.
   */
  bool gen_cob_style_;

  /**
   * True if we should omit calls to completion__() in CobClient class.
   */
  bool gen_no_client_completion_;

  /**
   * True if we should omit generating the default opeartors ==, != and <.
   */
  bool gen_no_default_operators_;

   /**
   * True if we should generate skeleton.
   */
  bool gen_no_skeleton_;

  /**
   * True if thrift has member(s)
   */
  bool has_members_;

  /**
   * Strings for namespace, computed once up front then used directly
   */

  std::string ns_open_;
  std::string ns_close_;

  /**
   * File streams, stored here to avoid passing them as parameters to every
   * function.
   */

  ofstream_with_content_based_conditional_update f_types_;
  ofstream_with_content_based_conditional_update f_types_impl_;
  ofstream_with_content_based_conditional_update f_types_tcc_;
  ofstream_with_content_based_conditional_update f_header_;
  ofstream_with_content_based_conditional_update f_service_;
  ofstream_with_content_based_conditional_update f_service_tcc_;

  // The ProcessorGenerator is used to generate parts of the code,
  // so it needs access to many of our protected members and methods.
  //
  // TODO: The code really should be cleaned up so that helper methods for
  // writing to the output files are separate from the generator classes
  // themselves.
  friend class ProcessorGenerator;
};

/**
 * Prepares for file generation by opening up the necessary file output
 * streams.
 */
void t_cpp_generator::init_generator() {
  // Make output directory
  MKDIR(get_out_dir().c_str());

  program_name_ = get_legal_program_name(program_name_);

  // Make output file
  string f_types_name = get_out_dir() + program_name_ + "_types.h";
  f_types_.open(f_types_name);

  string f_types_impl_name = get_out_dir() + program_name_ + "_types.cpp";
  f_types_impl_.open(f_types_impl_name.c_str());

  if (gen_templates_) {
    // If we don't open the stream, it appears to just discard data,
    // which is fine.
    string f_types_tcc_name = get_out_dir() + program_name_ + "_types.tcc";
    f_types_tcc_.open(f_types_tcc_name.c_str());
  }

  // Print header
  f_types_ << autogen_comment();
  f_types_impl_ << autogen_comment();
  f_types_tcc_ << autogen_comment();

  // Start ifndef
  f_types_ << "#ifndef " << program_name_ << "_TYPES_H" << endl << "#define " << program_name_
           << "_TYPES_H" << endl << endl;
  f_types_tcc_ << "#ifndef " << program_name_ << "_TYPES_TCC" << endl << "#define " << program_name_
               << "_TYPES_TCC" << endl << endl;

  // Include base types
  f_types_ << "#include <iosfwd>" << endl
           << endl
           << "#include <thrift/Thrift.h>" << endl
           << "#include <thrift/TApplicationException.h>" << endl
           << "#include <thrift/TBase.h>" << endl
           << "#include <thrift/protocol/TProtocol.h>" << endl
           << "#include <thrift/transport/TTransport.h>" << endl
           << endl;
  // Include C++xx compatibility header
  f_types_ << "#include <functional>" << endl;
  f_types_ << "#include <memory>" << endl;

  // Include other Thrift includes
  const vector<t_program*>& includes = program_->get_includes();
  for (auto include : includes) {
    f_types_ << "#include \"" << get_include_prefix(*include) << include->get_name()
             << "_types.h\"" << endl;

    // XXX(simpkins): If gen_templates_ is enabled, we currently assume all
    // included files were also generated with templates enabled.
    f_types_tcc_ << "#include \"" << get_include_prefix(*include) << include->get_name()
                 << "_types.tcc\"" << endl;
  }
  f_types_ << endl;

  // Include custom headers
  const vector<string>& cpp_includes = program_->get_cpp_includes();
  for (const auto & cpp_include : cpp_includes) {
    if (cpp_include[0] == '<') {
      f_types_ << "#include " << cpp_include << endl;
    } else {
      f_types_ << "#include \"" << cpp_include << "\"" << endl;
    }
  }
  f_types_ << endl;

  // Include the types file
  f_types_impl_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
                << "_types.h\"" << endl << endl;
  f_types_tcc_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
               << "_types.h\"" << endl << endl;

  // The swap() code needs <algorithm> for std::swap()
  f_types_impl_ << "#include <algorithm>" << endl;
  // for operator<<
  f_types_impl_ << "#include <ostream>" << endl << endl;
  f_types_impl_ << "#include <thrift/TToString.h>" << endl << endl;

  // Open namespace
  ns_open_ = namespace_open(program_->get_namespace("cpp"));
  ns_close_ = namespace_close(program_->get_namespace("cpp"));

  f_types_ << ns_open_ << endl << endl;

  f_types_impl_ << ns_open_ << endl << endl;

  f_types_tcc_ << ns_open_ << endl << endl;
}

/**
 * Closes the output files.
 */
void t_cpp_generator::close_generator() {
  // Close namespace
  f_types_ << ns_close_ << endl << endl;
  f_types_impl_ << ns_close_ << endl;
  f_types_tcc_ << ns_close_ << endl << endl;

  // Include the types.tcc file from the types header file,
  // so clients don't have to explicitly include the tcc file.
  // TODO(simpkins): Make this a separate option.
  if (gen_templates_) {
    f_types_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
             << "_types.tcc\"" << endl << endl;
  }

  // Close ifndef
  f_types_ << "#endif" << endl;
  f_types_tcc_ << "#endif" << endl;

  // Close output file
  f_types_.close();
  f_types_impl_.close();
  f_types_tcc_.close();

  string f_types_impl_name = get_out_dir() + program_name_ + "_types.cpp";

  if (!has_members_) {
    remove(f_types_impl_name.c_str());
  }
}

/**
 * Generates a typedef. This is just a simple 1-liner in C++
 *
 * @param ttypedef The type definition
 */
void t_cpp_generator::generate_typedef(t_typedef* ttypedef) {
  generate_java_doc(f_types_, ttypedef);
  f_types_ << indent() << "typedef " << type_name(ttypedef->get_type(), true) << " "
           << ttypedef->get_symbolic() << ";" << endl << endl;
}

void t_cpp_generator::generate_enum_constant_list(std::ostream& f,
                                                  const vector<t_enum_value*>& constants,
                                                  const char* prefix,
                                                  const char* suffix,
                                                  bool include_values) {
  f << " {" << endl;
  indent_up();

  vector<t_enum_value*>::const_iterator c_iter;
  bool first = true;
  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
    if (first) {
      first = false;
    } else {
      f << "," << endl;
    }
    generate_java_doc(f, *c_iter);
    indent(f) << prefix << (*c_iter)->get_name() << suffix;
    if (include_values) {
      f << " = " << (*c_iter)->get_value();
    }
  }

  f << endl;
  indent_down();
  indent(f) << "};" << endl;
}

/**
 * Generates code for an enumerated type. In C++, this is essentially the same
 * as the thrift definition itself, using the enum keyword in C++.
 *
 * @param tenum The enumeration
 */
void t_cpp_generator::generate_enum(t_enum* tenum) {
  vector<t_enum_value*> constants = tenum->get_constants();

  std::string enum_name = tenum->get_name();
  if (!gen_pure_enums_) {
    enum_name = "type";
    generate_java_doc(f_types_, tenum);
    f_types_ << indent() << "struct " << tenum->get_name() << " {" << endl;
    indent_up();
  }
  f_types_ << indent() << "enum " << enum_name;

  generate_enum_constant_list(f_types_, constants, "", "", true);

  if (!gen_pure_enums_) {
    indent_down();
    f_types_ << "};" << endl;
  }

  f_types_ << endl;

  /**
     Generate a character array of enum names for debugging purposes.
  */
  std::string prefix = "";
  if (!gen_pure_enums_) {
    prefix = tenum->get_name() + "::";
  }

  f_types_impl_ << indent() << "int _k" << tenum->get_name() << "Values[] =";
  generate_enum_constant_list(f_types_impl_, constants, prefix.c_str(), "", false);

  f_types_impl_ << indent() << "const char* _k" << tenum->get_name() << "Names[] =";
  generate_enum_constant_list(f_types_impl_, constants, "\"", "\"", false);

  f_types_ << indent() << "extern const std::map<int, const char*> _" << tenum->get_name()
           << "_VALUES_TO_NAMES;" << endl << endl;

  f_types_impl_ << indent() << "const std::map<int, const char*> _" << tenum->get_name()
                << "_VALUES_TO_NAMES(::apache::thrift::TEnumIterator(" << constants.size() << ", _k"
                << tenum->get_name() << "Values"
                << ", _k" << tenum->get_name() << "Names), "
                << "::apache::thrift::TEnumIterator(-1, nullptr, nullptr));" << endl << endl;

  generate_enum_ostream_operator_decl(f_types_, tenum);
  generate_enum_ostream_operator(f_types_impl_, tenum);

  generate_enum_to_string_helper_function_decl(f_types_, tenum);
  generate_enum_to_string_helper_function(f_types_impl_, tenum);

  has_members_ = true;
}

void t_cpp_generator::generate_enum_ostream_operator_decl(std::ostream& out, t_enum* tenum) {

  out << "std::ostream& operator<<(std::ostream& out, const ";
  if (gen_pure_enums_) {
    out << tenum->get_name();
  } else {
    out << tenum->get_name() << "::type&";
  }
  out << " val);" << endl;
  out << endl;
}

void t_cpp_generator::generate_enum_ostream_operator(std::ostream& out, t_enum* tenum) {

  // If we've been told the consuming application will provide an ostream
  // operator definition then we only make a declaration:

  if (!has_custom_ostream(tenum)) {
    out << "std::ostream& operator<<(std::ostream& out, const ";
    if (gen_pure_enums_) {
      out << tenum->get_name();
    } else {
      out << tenum->get_name() << "::type&";
    }
    out << " val) ";
    scope_up(out);

    out << indent() << "std::map<int, const char*>::const_iterator it = _"
             << tenum->get_name() << "_VALUES_TO_NAMES.find(val);" << endl;
    out << indent() << "if (it != _" << tenum->get_name() << "_VALUES_TO_NAMES.end()) {" << endl;
    indent_up();
    out << indent() << "out << it->second;" << endl;
    indent_down();
    out << indent() << "} else {" << endl;
    indent_up();
    out << indent() << "out << static_cast<int>(val);" << endl;
    indent_down();
    out << indent() << "}" << endl;

    out << indent() << "return out;" << endl;
    scope_down(out);
    out << endl;
  }
}

void t_cpp_generator::generate_enum_to_string_helper_function_decl(std::ostream& out, t_enum* tenum) {
  out << "std::string to_string(const ";
  if (gen_pure_enums_) {
    out << tenum->get_name();
  } else {
    out << tenum->get_name() << "::type&";
  }
  out << " val);" << endl;
  out << endl;
}

void t_cpp_generator::generate_enum_to_string_helper_function(std::ostream& out, t_enum* tenum) {
  if (!has_custom_ostream(tenum)) {
    out << "std::string to_string(const ";
    if (gen_pure_enums_) {
      out << tenum->get_name();
    } else {
      out << tenum->get_name() << "::type&";
    }
    out << " val) " ;
	scope_up(out);

    out << indent() << "std::map<int, const char*>::const_iterator it = _"
             << tenum->get_name() << "_VALUES_TO_NAMES.find(val);" << endl;
    out << indent() << "if (it != _" << tenum->get_name() << "_VALUES_TO_NAMES.end()) {" << endl;
    indent_up();
    out << indent() << "return std::string(it->second);" << endl;
    indent_down();
    out << indent() << "} else {" << endl;
    indent_up();
    out << indent() << "return std::to_string(static_cast<int>(val));" << endl;
    indent_down();
    out << indent() << "}" << endl;

    scope_down(out);
    out << endl;
  }
}

/**
 * Generates a class that holds all the constants.
 */
void t_cpp_generator::generate_consts(std::vector<t_const*> consts) {
  string f_consts_name = get_out_dir() + program_name_ + "_constants.h";
  ofstream_with_content_based_conditional_update f_consts;
  if (consts.size() > 0) {
    f_consts.open(f_consts_name);

    string f_consts_impl_name = get_out_dir() + program_name_ + "_constants.cpp";
    ofstream_with_content_based_conditional_update f_consts_impl;
    f_consts_impl.open(f_consts_impl_name);

    // Print header
    f_consts << autogen_comment();
    f_consts_impl << autogen_comment();

    // Start ifndef
    f_consts << "#ifndef " << program_name_ << "_CONSTANTS_H" << endl << "#define " << program_name_
             << "_CONSTANTS_H" << endl << endl << "#include \"" << get_include_prefix(*get_program())
             << program_name_ << "_types.h\"" << endl << endl << ns_open_ << endl << endl;

    f_consts_impl << "#include \"" << get_include_prefix(*get_program()) << program_name_
                  << "_constants.h\"" << endl << endl << ns_open_ << endl << endl;

    f_consts << "class " << program_name_ << "Constants {" << endl << " public:" << endl << "  "
             << program_name_ << "Constants();" << endl << endl;
    indent_up();
    vector<t_const*>::iterator c_iter;
    for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
      string name = (*c_iter)->get_name();
      t_type* type = (*c_iter)->get_type();
      f_consts << indent() << type_name(type) << " " << name << ";" << endl;
    }
    indent_down();
    f_consts << "};" << endl;

    f_consts_impl << "const " << program_name_ << "Constants g_" << program_name_ << "_constants;"
                  << endl << endl << program_name_ << "Constants::" << program_name_
                  << "Constants() {" << endl;
    indent_up();
    for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
      print_const_value(f_consts_impl,
                        (*c_iter)->get_name(),
                        (*c_iter)->get_type(),
                        (*c_iter)->get_value());
    }
    indent_down();
    indent(f_consts_impl) << "}" << endl;

    f_consts << endl << "extern const " << program_name_ << "Constants g_" << program_name_
             << "_constants;" << endl << endl << ns_close_ << endl << endl << "#endif" << endl;
    f_consts.close();

    f_consts_impl << endl << ns_close_ << endl << endl;
    f_consts_impl.close();
  }
}

/**
 * Prints the value of a constant with the given type. Note that type checking
 * is NOT performed in this function as it is always run beforehand using the
 * validate_types method in main.cc
 */
void t_cpp_generator::print_const_value(ostream& out,
                                        string name,
                                        t_type* type,
                                        t_const_value* value) {
  type = get_true_type(type);
  if (type->is_base_type()) {
    string v2 = render_const_value(out, name, type, value);
    indent(out) << name << " = " << v2 << ";" << endl << endl;
  } else if (type->is_enum()) {
    indent(out) << name << " = (" << type_name(type) << ")" << value->get_integer() << ";" << endl
                << endl;
  } else if (type->is_struct() || type->is_xception()) {
    const vector<t_field*>& fields = ((t_struct*)type)->get_members();
    vector<t_field*>::const_iterator f_iter;
    const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
    map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
    bool is_nonrequired_field = false;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      t_type* field_type = nullptr;
      is_nonrequired_field = false;
      for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
        if ((*f_iter)->get_name() == v_iter->first->get_string()) {
          field_type = (*f_iter)->get_type();
          is_nonrequired_field = (*f_iter)->get_req() != t_field::T_REQUIRED;
        }
      }
      if (field_type == nullptr) {
        throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
      }
      string val = render_const_value(out, name, field_type, v_iter->second);
      indent(out) << name << "." << v_iter->first->get_string() << " = " << val << ";" << endl;
      if (is_nonrequired_field) {
        indent(out) << name << ".__isset." << v_iter->first->get_string() << " = true;" << endl;
      }
    }
    out << endl;
  } else if (type->is_map()) {
    t_type* ktype = ((t_map*)type)->get_key_type();
    t_type* vtype = ((t_map*)type)->get_val_type();
    const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
    map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      string key = render_const_value(out, name, ktype, v_iter->first);
      string val = render_const_value(out, name, vtype, v_iter->second);
      indent(out) << name << ".insert(std::make_pair(" << key << ", " << val << "));" << endl;
    }
    out << endl;
  } else if (type->is_list()) {
    t_type* etype = ((t_list*)type)->get_elem_type();
    const vector<t_const_value*>& val = value->get_list();
    vector<t_const_value*>::const_iterator v_iter;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      string val = render_const_value(out, name, etype, *v_iter);
      indent(out) << name << ".push_back(" << val << ");" << endl;
    }
    out << endl;
  } else if (type->is_set()) {
    t_type* etype = ((t_set*)type)->get_elem_type();
    const vector<t_const_value*>& val = value->get_list();
    vector<t_const_value*>::const_iterator v_iter;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      string val = render_const_value(out, name, etype, *v_iter);
      indent(out) << name << ".insert(" << val << ");" << endl;
    }
    out << endl;
  } else {
    throw "INVALID TYPE IN print_const_value: " + type->get_name();
  }
}

/**
 *
 */
string t_cpp_generator::render_const_value(ostream& out,
                                           string name,
                                           t_type* type,
                                           t_const_value* value) {
  (void)name;
  std::ostringstream render;

  if (type->is_base_type()) {
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_STRING:
      render << '"' << get_escaped_string(value) << '"';
      break;
    case t_base_type::TYPE_BOOL:
      render << ((value->get_integer() > 0) ? "true" : "false");
      break;
    case t_base_type::TYPE_I8:
    case t_base_type::TYPE_I16:
    case t_base_type::TYPE_I32:
      render << value->get_integer();
      break;
    case t_base_type::TYPE_I64:
      render << value->get_integer() << "LL";
      break;
    case t_base_type::TYPE_DOUBLE:
      if (value->get_type() == t_const_value::CV_INTEGER) {
        render << "static_cast<double>(" << value->get_integer() << ")";
      } else {
        render << emit_double_as_string(value->get_double());
      }
      break;
    default:
      throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
    }
  } else if (type->is_enum()) {
    render << "(" << type_name(type) << ")" << value->get_integer();
  } else {
    string t = tmp("tmp");
    indent(out) << type_name(type) << " " << t << ";" << endl;
    print_const_value(out, t, type, value);
    render << t;
  }

  return render.str();
}

void t_cpp_generator::generate_forward_declaration(t_struct* tstruct) {
  // Forward declare struct def
  f_types_ << indent() << "class " << tstruct->get_name() << ";" << endl << endl;
}

/**
 * Generates a struct definition for a thrift data type. This is a class
 * with data members and a read/write() function, plus a mirroring isset
 * inner class.
 *
 * @param tstruct The struct definition
 */
void t_cpp_generator::generate_cpp_struct(t_struct* tstruct, bool is_exception) {
  generate_struct_declaration(f_types_, tstruct, is_exception, false, true, true, true, true);
  generate_struct_definition(f_types_impl_, f_types_impl_, tstruct, true, true);

  std::ostream& out = (gen_templates_ ? f_types_tcc_ : f_types_impl_);
  generate_struct_reader(out, tstruct);
  generate_struct_writer(out, tstruct);
  generate_struct_swap(f_types_impl_, tstruct);
  generate_copy_constructor(f_types_impl_, tstruct, is_exception);
  if (gen_moveable_) {
    generate_move_constructor(f_types_impl_, tstruct, is_exception);
  }
  generate_assignment_operator(f_types_impl_, tstruct);
  if (gen_moveable_) {
    generate_move_assignment_operator(f_types_impl_, tstruct);
  }

  if (!has_custom_ostream(tstruct)) {
    generate_struct_print_method(f_types_impl_, tstruct);
  }

  if (is_exception) {
    generate_exception_what_method(f_types_impl_, tstruct);
  }

  has_members_ = true;
}

void t_cpp_generator::generate_copy_constructor(ostream& out,
                                                t_struct* tstruct,
                                                bool is_exception) {
  generate_constructor_helper(out, tstruct, is_exception, /*is_move=*/false);
}

void t_cpp_generator::generate_move_constructor(ostream& out,
                                                t_struct* tstruct,
                                                bool is_exception) {
  generate_constructor_helper(out, tstruct, is_exception, /*is_move=*/true);
}

namespace {
// Helper to convert a variable to rvalue, if move is enabled
std::string maybeMove(std::string const& other, bool move) {
  if (move) {
    return "std::move(" + other + ")";
  }
  return other;
}
}

void t_cpp_generator::generate_constructor_helper(ostream& out,
                                                  t_struct* tstruct,
                                                  bool is_exception,
                                                  bool is_move) {

  std::string tmp_name = tmp("other");

  indent(out) << tstruct->get_name() << "::" << tstruct->get_name();

  if (is_move) {
    out << "(" << tstruct->get_name() << "&& ";
  } else {
    out << "(const " << tstruct->get_name() << "& ";
  }
  out << tmp_name << ") ";
  if(is_move || is_struct_storage_not_throwing(tstruct))
    out << "noexcept ";
  if (is_exception)
    out << ": TException() ";
  out << "{" << endl;
  indent_up();

  const vector<t_field*>& members = tstruct->get_members();

  // eliminate compiler unused warning
  if (members.empty())
    indent(out) << "(void) " << tmp_name << ";" << endl;

  vector<t_field*>::const_iterator f_iter;
  bool has_nonrequired_fields = false;
  for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {
    if ((*f_iter)->get_req() != t_field::T_REQUIRED)
      has_nonrequired_fields = true;
    indent(out) << (*f_iter)->get_name() << " = "
                << maybeMove(
                    tmp_name + "." + (*f_iter)->get_name(), 
                    is_move && is_complex_type((*f_iter)->get_type()))
                << ";" << endl;
  }

  if (has_nonrequired_fields) {
    indent(out) << "__isset = " << maybeMove(tmp_name + ".__isset", false) << ";" << endl;
  }

  indent_down();
  indent(out) << "}" << endl;
}

void t_cpp_generator::generate_assignment_operator(ostream& out, t_struct* tstruct) {
  generate_assignment_helper(out, tstruct, /*is_move=*/false);
}

void t_cpp_generator::generate_move_assignment_operator(ostream& out, t_struct* tstruct) {
  generate_assignment_helper(out, tstruct, /*is_move=*/true);
}

void t_cpp_generator::generate_assignment_helper(ostream& out, t_struct* tstruct, bool is_move) {
  std::string tmp_name = tmp("other");

  indent(out) << tstruct->get_name() << "& " << tstruct->get_name() << "::operator=(";

  if (is_move) {
    out << tstruct->get_name() << "&& ";
  } else {
    out << "const " << tstruct->get_name() << "& ";
  }
  out << tmp_name << ") ";
  if(is_move || is_struct_storage_not_throwing(tstruct))
    out << "noexcept ";
  out << "{" << endl;
  indent_up();

  const vector<t_field*>& members = tstruct->get_members();

  // eliminate compiler unused warning
  if (members.empty())
    indent(out) << "(void) " << tmp_name << ";" << endl;

  vector<t_field*>::const_iterator f_iter;
  bool has_nonrequired_fields = false;
  for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {
    if ((*f_iter)->get_req() != t_field::T_REQUIRED)
      has_nonrequired_fields = true;
    indent(out) << (*f_iter)->get_name() << " = "
                << maybeMove(
                    tmp_name + "." + (*f_iter)->get_name(), 
                    is_move && is_complex_type((*f_iter)->get_type()))
                << ";" << endl;
  }
  if (has_nonrequired_fields) {
    indent(out) << "__isset = " << maybeMove(tmp_name + ".__isset", false) << ";" << endl;
  }

  indent(out) << "return *this;" << endl;
  indent_down();
  indent(out) << "}" << endl;
}

/**
 * Writes the struct declaration into the header file
 *
 * @param out Output stream
 * @param tstruct The struct
 */
void t_cpp_generator::generate_struct_declaration(ostream& out,
                                                  t_struct* tstruct,
                                                  bool is_exception,
                                                  bool pointers,
                                                  bool read,
                                                  bool write,
                                                  bool swap,
                                                  bool is_user_struct) {
  string extends = "";
  if (is_exception) {
    extends = " : public ::apache::thrift::TException";
  } else {
    if (is_user_struct && !gen_templates_) {
      extends = " : public virtual ::apache::thrift::TBase";
    }
  }

  // Get members
  vector<t_field*>::const_iterator m_iter;
  const vector<t_field*>& members = tstruct->get_members();

  // Write the isset structure declaration outside the class. This makes
  // the generated code amenable to processing by SWIG.
  // We only declare the struct if it gets used in the class.

  // Isset struct has boolean fields, but only for non-required fields.
  bool has_nonrequired_fields = false;
  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
    if ((*m_iter)->get_req() != t_field::T_REQUIRED)
      has_nonrequired_fields = true;
  }

  if (has_nonrequired_fields && (!pointers || read)) {

    out << indent() << "typedef struct _" << tstruct->get_name() << "__isset {" << endl;
    indent_up();

    indent(out) << "_" << tstruct->get_name() << "__isset() ";
    bool first = true;
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
      if ((*m_iter)->get_req() == t_field::T_REQUIRED) {
        continue;
      }
      string isSet = ((*m_iter)->get_value() != nullptr) ? "true" : "false";
      if (first) {
        first = false;
        out << ": " << (*m_iter)->get_name() << "(" << isSet << ")";
      } else {
        out << ", " << (*m_iter)->get_name() << "(" << isSet << ")";
      }
    }
    out << " {}" << endl;

    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
      if ((*m_iter)->get_req() != t_field::T_REQUIRED) {
        indent(out) << "bool " << (*m_iter)->get_name() << " :1;" << endl;
      }
    }

    indent_down();
    indent(out) << "} _" << tstruct->get_name() << "__isset;" << endl;
  }

  out << endl;

  generate_java_doc(out, tstruct);

  // Open struct def
  out << indent() << "class " << tstruct->get_name() << extends << " {" << endl << indent()
      << " public:" << endl << endl;
  indent_up();

  if (!pointers) {
    bool ok_noexcept = is_struct_storage_not_throwing(tstruct);
    // Copy constructor
    indent(out) << tstruct->get_name() << "(const " << tstruct->get_name() << "&)"
                << (ok_noexcept? " noexcept" : "") << ';' << endl;

    // Move constructor
    if (gen_moveable_) {
      indent(out) << tstruct->get_name() << "(" << tstruct->get_name() << "&&) noexcept;" 
                  << endl;
    }

    // Assignment Operator
    indent(out) << tstruct->get_name() << "& operator=(const " << tstruct->get_name() << "&)"
                << (ok_noexcept? " noexcept" : "") << ';' << endl;

    // Move assignment operator
    if (gen_moveable_) {
      indent(out) << tstruct->get_name() << "& operator=(" << tstruct->get_name() << "&&) noexcept;" 
                  << endl;
    }

    bool has_default_value = false;
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
      t_type* t = get_true_type((*m_iter)->get_type());
      if (is_reference(*m_iter) || t->is_string()) {
        t_const_value* cv = (*m_iter)->get_value();
        if (cv != nullptr) {
          has_default_value = true;
          break;
        }
      }
    }

    // Default constructor
    std::string clsname_ctor = tstruct->get_name() + "()";
    indent(out) << clsname_ctor << (has_default_value ? "" : " noexcept");

    bool init_ctor = false;
    std::string args_indent(
      indent().size() + clsname_ctor.size() + (has_default_value ? 3 : -1), ' ');

    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
      t_type* t = get_true_type((*m_iter)->get_type());
      if (t->is_base_type() || t->is_enum() || is_reference(*m_iter)) {
        string dval;
        t_const_value* cv = (*m_iter)->get_value();
        if (cv != nullptr) {
          dval += render_const_value(out, (*m_iter)->get_name(), t, cv);
        } else if (t->is_enum()) {
          dval += "static_cast<" + type_name(t) + ">(0)";
        } else {
          dval += (t->is_string() || is_reference(*m_iter)) ? "" : "0";
        }
        if (!init_ctor) {
          init_ctor = true;
          if(has_default_value) {
            out << " : ";
          } else {
            out << '\n' << args_indent << ": ";
            args_indent.append("  ");
          }
        } else {
          out << ",\n" << args_indent;
        }
        out << (*m_iter)->get_name() << "(" << dval << ")";
      }
    }
    out << " {" << endl;
    indent_up();
    // TODO(dreiss): When everything else in Thrift is perfect,
    // do more of these in the initializer list.
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
      t_type* t = get_true_type((*m_iter)->get_type());

      if (!t->is_base_type()) {
        t_const_value* cv = (*m_iter)->get_value();
        if (cv != nullptr) {
          print_const_value(out, (*m_iter)->get_name(), t, cv);
        }
      }
    }
    scope_down(out);
  }

  if (tstruct->annotations_.find("final") == tstruct->annotations_.end()) {
    out << endl << indent() << "virtual ~" << tstruct->get_name() << "() noexcept;" << endl;
  }

  // Declare all fields
  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
	generate_java_doc(out, *m_iter);
    indent(out) << declare_field(*m_iter,
                                 false,
                                 (pointers && !(*m_iter)->get_type()->is_xception()),
                                 !read) << endl;
  }

  // Add the __isset data member if we need it, using the definition from above
  if (has_nonrequired_fields && (!pointers || read)) {
    out << endl << indent() << "_" << tstruct->get_name() << "__isset __isset;" << endl;
  }

  // Create a setter function for each field
  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
    if (pointers) {
      continue;
    }
    if (is_reference((*m_iter))) {
      out << endl << indent() << "void __set_" << (*m_iter)->get_name() << "(::std::shared_ptr<"
          << type_name((*m_iter)->get_type(), false, false) << ">";
      out << " val);" << endl;
    } else {
      out << endl << indent() << "void __set_" << (*m_iter)->get_name() << "("
          << type_name((*m_iter)->get_type(), false, true);
      out << " val);" << endl;
    }
  }
  out << endl;

  if (!pointers) {
    // Should we generate default operators?
    if (!gen_no_default_operators_) {
      // Generate an equality testing operator.  Make it inline since the compiler
      // will do a better job than we would when deciding whether to inline it.
      out << indent() << "bool operator == (const " << tstruct->get_name() << " & "
          << (members.size() > 0 ? "rhs" : "/* rhs */") << ") const" << endl;
      scope_up(out);
      for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
        // Most existing Thrift code does not use isset or optional/required,
        // so we treat "default" fields as required.
        if ((*m_iter)->get_req() != t_field::T_OPTIONAL) {
          out << indent() << "if (!(" << (*m_iter)->get_name() << " == rhs."
              << (*m_iter)->get_name() << "))" << endl << indent() << "  return false;" << endl;
        } else {
          out << indent() << "if (__isset." << (*m_iter)->get_name() << " != rhs.__isset."
              << (*m_iter)->get_name() << ")" << endl << indent() << "  return false;" << endl
              << indent() << "else if (__isset." << (*m_iter)->get_name() << " && !("
              << (*m_iter)->get_name() << " == rhs." << (*m_iter)->get_name() << "))" << endl
              << indent() << "  return false;" << endl;
        }
      }
      indent(out) << "return true;" << endl;
      scope_down(out);
      out << indent() << "bool operator != (const " << tstruct->get_name() << " &rhs) const {"
          << endl << indent() << "  return !(*this == rhs);" << endl << indent() << "}" << endl
          << endl;

      // Generate the declaration of a less-than operator.  This must be
      // implemented by the application developer if they wish to use it.  (They
      // will get a link error if they try to use it without an implementation.)
      out << indent() << "bool operator < (const " << tstruct->get_name() << " & ) const;" << endl
          << endl;
    }
  }

  if (read) {
    if (gen_templates_) {
      out << indent() << "template <class Protocol_>" << endl << indent()
          << "uint32_t read(Protocol_* iprot);" << endl;
    } else {
      out << indent() << "uint32_t read("
          << "::apache::thrift::protocol::TProtocol* iprot)";
      if(!is_exception && !extends.empty())
        out << " override";
      out << ';' << endl;
    }
  }
  if (write) {
    if (gen_templates_) {
      out << indent() << "template <class Protocol_>" << endl << indent()
          << "uint32_t write(Protocol_* oprot) const;" << endl;
    } else {
      out << indent() << "uint32_t write("
          << "::apache::thrift::protocol::TProtocol* oprot) const";
      if(!is_exception && !extends.empty())
        out << " override";
      out << ';' << endl;
    }
  }
  out << endl;

  if (is_user_struct && !has_custom_ostream(tstruct)) {
    out << indent() << "virtual ";
    generate_struct_print_method_decl(out, nullptr);
    out << ";" << endl;
  }

  // std::exception::what()
  if (is_exception) {
    out << indent() << "mutable std::string thriftTExceptionMessageHolder_;" << endl;
    out << indent();
    generate_exception_what_method_decl(out, tstruct, false);
    out << ";" << endl;
  }

  indent_down();
  indent(out) << "};" << endl << endl;

  if (swap) {
    // Generate a namespace-scope swap() function
    if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
      out << indent() << "void swap(" << tstruct->get_name() << " &a1, " << tstruct->get_name()
          << " &a2);" << endl << endl;
    } else {
       out << indent() << "void swap(" << tstruct->get_name() << " &a, " << tstruct->get_name()
           << " &b);" << endl << endl;
    }
  }

  if (is_user_struct) {
    generate_struct_ostream_operator_decl(out, tstruct);
  }
}

void t_cpp_generator::generate_struct_definition(ostream& out,
                                                 ostream& force_cpp_out,
                                                 t_struct* tstruct,
                                                 bool setters,
                                                 bool is_user_struct) {
  // Get members
  vector<t_field*>::const_iterator m_iter;
  const vector<t_field*>& members = tstruct->get_members();

  // Destructor
  if (tstruct->annotations_.find("final") == tstruct->annotations_.end()) {
    force_cpp_out << endl << indent() << tstruct->get_name() << "::~" << tstruct->get_name()
                  << "() noexcept {" << endl;
    indent_up();

    indent_down();
    force_cpp_out << indent() << "}" << endl << endl;
  }

  // Create a setter function for each field
  if (setters) {
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
      if (is_reference((*m_iter))) {
        out << endl << indent() << "void " << tstruct->get_name() << "::__set_"
            << (*m_iter)->get_name() << "(::std::shared_ptr<"
            << type_name((*m_iter)->get_type(), false, false) << ">";
        out << " val) {" << endl;
      } else {
        out << endl << indent() << "void " << tstruct->get_name() << "::__set_"
            << (*m_iter)->get_name() << "(" << type_name((*m_iter)->get_type(), false, true);
        out << " val) {" << endl;
      }
      indent_up();
      out << indent() << "this->" << (*m_iter)->get_name() << " = val;" << endl;
      indent_down();

      // assume all fields are required except optional fields.
      // for optional fields change __isset.name to true
      bool is_optional = (*m_iter)->get_req() == t_field::T_OPTIONAL;
      if (is_optional) {
        out << indent() << indent() << "__isset." << (*m_iter)->get_name() << " = true;" << endl;
      }
      out << indent() << "}" << endl;
    }
  }
  if (is_user_struct) {
    generate_struct_ostream_operator(out, tstruct);
  }
  out << endl;
}

/**
 * Makes a helper function to gen a struct reader.
 *
 * @param out Stream to write to
 * @param tstruct The struct
 */
void t_cpp_generator::generate_struct_reader(ostream& out, t_struct* tstruct, bool pointers) {
  if (gen_templates_) {
    out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
        << tstruct->get_name() << "::read(Protocol_* iprot) {" << endl;
  } else {
    indent(out) << "uint32_t " << tstruct->get_name()
                << "::read(::apache::thrift::protocol::TProtocol* iprot) {" << endl;
  }
  indent_up();

  const vector<t_field*>& fields = tstruct->get_members();
  vector<t_field*>::const_iterator f_iter;

  // Declare stack tmp variables
  out << endl
      << indent() << "::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);" << endl
      << indent() << "uint32_t xfer = 0;" << endl
      << indent() << "std::string fname;" << endl
      << indent() << "::apache::thrift::protocol::TType ftype;" << endl
      << indent() << "int16_t fid;" << endl
      << endl
      << indent() << "xfer += iprot->readStructBegin(fname);" << endl
      << endl
      << indent() << "using ::apache::thrift::protocol::TProtocolException;" << endl
      << endl;

  // Required variables aren't in __isset, so we need tmp vars to check them.
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    if ((*f_iter)->get_req() == t_field::T_REQUIRED)
      indent(out) << "bool isset_" << (*f_iter)->get_name() << " = false;" << endl;
  }
  out << endl;

  // Loop over reading in fields
  indent(out) << "while (true)" << endl;
  scope_up(out);

  // Read beginning field marker
  indent(out) << "xfer += iprot->readFieldBegin(fname, ftype, fid);" << endl;

  // Check for field STOP marker
  out << indent() << "if (ftype == ::apache::thrift::protocol::T_STOP) {" << endl << indent()
      << "  break;" << endl << indent() << "}" << endl;

  if (fields.empty()) {
    out << indent() << "xfer += iprot->skip(ftype);" << endl;
  } else {
    // Switch statement on the field we are reading
    indent(out) << "switch (fid)" << endl;

    scope_up(out);

    // Generate deserialization code for known cases
    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
      indent(out) << "case " << (*f_iter)->get_key() << ":" << endl;
      indent_up();
      indent(out) << "if (ftype == " << type_to_enum((*f_iter)->get_type()) << ") {" << endl;
      indent_up();

      const char* isset_prefix = ((*f_iter)->get_req() != t_field::T_REQUIRED) ? "this->__isset."
                                                                               : "isset_";

#if 0
          // This code throws an exception if the same field is encountered twice.
          // We've decided to leave it out for performance reasons.
          // TODO(dreiss): Generate this code and "if" it out to make it easier
          // for people recompiling thrift to include it.
          out <<
            indent() << "if (" << isset_prefix << (*f_iter)->get_name() << ")" << endl <<
            indent() << "  throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
#endif

      if (pointers && !(*f_iter)->get_type()->is_xception()) {
        generate_deserialize_field(out, *f_iter, "(*(this->", "))");
      } else {
        generate_deserialize_field(out, *f_iter, "this->");
      }
      out << indent() << isset_prefix << (*f_iter)->get_name() << " = true;" << endl;
      indent_down();
      out << indent() << "} else {" << endl << indent() << "  xfer += iprot->skip(ftype);" << endl
          <<
          // TODO(dreiss): Make this an option when thrift structs
          // have a common base class.
          // indent() << "  throw TProtocolException(TProtocolException::INVALID_DATA);" << endl <<
          indent() << "}" << endl << indent() << "break;" << endl;
      indent_down();
    }

    // In the default case we skip the field
    out << indent() << "default:" << endl << indent() << "  xfer += iprot->skip(ftype);" << endl
        << indent() << "  break;" << endl;

    scope_down(out);
  } //!fields.empty()
  // Read field end marker
  indent(out) << "xfer += iprot->readFieldEnd();" << endl;

  scope_down(out);

  out << endl << indent() << "xfer += iprot->readStructEnd();" << endl;

  // Throw if any required fields are missing.
  // We do this after reading the struct end so that
  // there might possibly be a chance of continuing.
  out << endl;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    if ((*f_iter)->get_req() == t_field::T_REQUIRED)
      out << indent() << "if (!isset_" << (*f_iter)->get_name() << ')' << endl << indent()
          << "  throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
  }

  indent(out) << "return xfer;" << endl;

  indent_down();
  indent(out) << "}" << endl << endl;
}

/**
 * Generates the write function.
 *
 * @param out Stream to write to
 * @param tstruct The struct
 */
void t_cpp_generator::generate_struct_writer(ostream& out, t_struct* tstruct, bool pointers) {
  string name = tstruct->get_name();
  const vector<t_field*>& fields = tstruct->get_sorted_members();
  vector<t_field*>::const_iterator f_iter;

  if (gen_templates_) {
    out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
        << tstruct->get_name() << "::write(Protocol_* oprot) const {" << endl;
  } else {
    indent(out) << "uint32_t " << tstruct->get_name()
                << "::write(::apache::thrift::protocol::TProtocol* oprot) const {" << endl;
  }
  indent_up();

  out << indent() << "uint32_t xfer = 0;" << endl;

  indent(out) << "::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);" << endl;
  indent(out) << "xfer += oprot->writeStructBegin(\"" << name << "\");" << endl;

  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    bool check_if_set = (*f_iter)->get_req() == t_field::T_OPTIONAL
                        || (*f_iter)->get_type()->is_xception();
    if (check_if_set) {
      out << endl << indent() << "if (this->__isset." << (*f_iter)->get_name() << ") {" << endl;
      indent_up();
    } else {
      out << endl;
    }

    // Write field header
    out << indent() << "xfer += oprot->writeFieldBegin("
        << "\"" << (*f_iter)->get_name() << "\", " << type_to_enum((*f_iter)->get_type()) << ", "
        << (*f_iter)->get_key() << ");" << endl;
    // Write field contents
    if (pointers && !(*f_iter)->get_type()->is_xception()) {
      generate_serialize_field(out, *f_iter, "(*(this->", "))");
    } else {
      generate_serialize_field(out, *f_iter, "this->");
    }
    // Write field closer
    indent(out) << "xfer += oprot->writeFieldEnd();" << endl;
    if (check_if_set) {
      indent_down();
      indent(out) << '}';
    }
  }

  out << endl;

  // Write the struct map
  out << indent() << "xfer += oprot->writeFieldStop();" << endl << indent()
      << "xfer += oprot->writeStructEnd();" << endl << indent()
      << "return xfer;" << endl;

  indent_down();
  indent(out) << "}" << endl << endl;
}

/**
 * Struct writer for result of a function, which can have only one of its
 * fields set and does a conditional if else look up into the __isset field
 * of the struct.
 *
 * @param out Output stream
 * @param tstruct The result struct
 */
void t_cpp_generator::generate_struct_result_writer(ostream& out,
                                                    t_struct* tstruct,
                                                    bool pointers) {
  string name = tstruct->get_name();
  const vector<t_field*>& fields = tstruct->get_sorted_members();
  vector<t_field*>::const_iterator f_iter;

  if (gen_templates_) {
    out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
        << tstruct->get_name() << "::write(Protocol_* oprot) const {" << endl;
  } else {
    indent(out) << "uint32_t " << tstruct->get_name()
                << "::write(::apache::thrift::protocol::TProtocol* oprot) const {" << endl;
  }
  indent_up();

  out << endl << indent() << "uint32_t xfer = 0;" << endl << endl;

  indent(out) << "xfer += oprot->writeStructBegin(\"" << name << "\");" << endl;

  bool first = true;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    if (first) {
      first = false;
      out << endl << indent() << "if ";
    } else {
      out << " else if ";
    }

    out << "(this->__isset." << (*f_iter)->get_name() << ") {" << endl;

    indent_up();

    // Write field header
    out << indent() << "xfer += oprot->writeFieldBegin("
        << "\"" << (*f_iter)->get_name() << "\", " << type_to_enum((*f_iter)->get_type()) << ", "
        << (*f_iter)->get_key() << ");" << endl;
    // Write field contents
    if (pointers) {
      generate_serialize_field(out, *f_iter, "(*(this->", "))");
    } else {
      generate_serialize_field(out, *f_iter, "this->");
    }
    // Write field closer
    indent(out) << "xfer += oprot->writeFieldEnd();" << endl;

    indent_down();
    indent(out) << "}";
  }

  // Write the struct map
  out << endl << indent() << "xfer += oprot->writeFieldStop();" << endl << indent()
      << "xfer += oprot->writeStructEnd();" << endl << indent() << "return xfer;" << endl;

  indent_down();
  indent(out) << "}" << endl << endl;
}

/**
 * Generates the swap function.
 *
 * @param out Stream to write to
 * @param tstruct The struct
 */
void t_cpp_generator::generate_struct_swap(ostream& out, t_struct* tstruct) {
  if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
    out << indent() << "void swap(" << tstruct->get_name() << " &a1, " << tstruct->get_name()
        << " &a2) {" << endl; 
  } else {
    out << indent() << "void swap(" << tstruct->get_name() << " &a, " << tstruct->get_name()
        << " &b) {" << endl;
  }

  indent_up();

  // Let argument-dependent name lookup find the correct swap() function to
  // use based on the argument types.  If none is found in the arguments'
  // namespaces, fall back to ::std::swap().
  out << indent() << "using ::std::swap;" << endl;

  bool has_nonrequired_fields = false;
  const vector<t_field*>& fields = tstruct->get_members();
  for (auto tfield : fields) {
    if (tfield->get_req() != t_field::T_REQUIRED) {
      has_nonrequired_fields = true;
    }

    if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
      out << indent() << "swap(a1." << tfield->get_name() << ", a2." << tfield->get_name() << ");"
          << endl;
    } else {
      out << indent() << "swap(a." << tfield->get_name() << ", b." << tfield->get_name() << ");"
          << endl;
    }
  }

  if (has_nonrequired_fields) {
    if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
      out << indent() << "swap(a1.__isset, a2.__isset);" << endl; 
    } else {
      out << indent() << "swap(a.__isset, b.__isset);" << endl;
    }
  }

  // handle empty structs
  if (fields.size() == 0) {
    if (tstruct->get_name() == "a" || tstruct->get_name() == "b") {
      out << indent() << "(void) a1;" << endl;
      out << indent() << "(void) a2;" << endl;
    } else {
      out << indent() << "(void) a;" << endl;
      out << indent() << "(void) b;" << endl;
    }
  }

  scope_down(out);
  out << endl;
}

void t_cpp_generator::generate_struct_ostream_operator_decl(std::ostream& out, t_struct* tstruct) {
  out << "std::ostream& operator<<(std::ostream& out, const "
      << tstruct->get_name()
      << "& obj);" << endl;
  out << endl;
}

void t_cpp_generator::generate_struct_ostream_operator(std::ostream& out, t_struct* tstruct) {
  if (!has_custom_ostream(tstruct)) {
    // thrift defines this behavior
    out << "std::ostream& operator<<(std::ostream& out, const "
        << tstruct->get_name()
        << "& obj)" << endl;
    scope_up(out);
    out << indent() << "obj.printTo(out);" << endl
        << indent() << "return out;" << endl;
    scope_down(out);
    out << endl;
  }
}

void t_cpp_generator::generate_struct_print_method_decl(std::ostream& out, t_struct* tstruct) {
  out << "void ";
  if (tstruct) {
    out << tstruct->get_name() << "::";
  }
  out << "printTo(std::ostream& out) const";
}

void t_cpp_generator::generate_exception_what_method_decl(std::ostream& out,
                                                          t_struct* tstruct,
                                                          bool external) {
  out << "const char* ";
  if (external) {
    out << tstruct->get_name() << "::";
  }
  out << "what() const noexcept";
  if(!external)
    out << " override";
}

namespace struct_ostream_operator_generator {
void generate_required_field_value(std::ostream& out, const t_field* field) {
  out << " << to_string(" << field->get_name() << ")";
}

void generate_optional_field_value(std::ostream& out, const t_field* field) {
  out << "; (__isset." << field->get_name() << " ? (out";
  generate_required_field_value(out, field);
  out << ") : (out << \"<null>\"))";
}

void generate_field_value(std::ostream& out, const t_field* field) {
  if (field->get_req() == t_field::T_OPTIONAL)
    generate_optional_field_value(out, field);
  else
    generate_required_field_value(out, field);
}

void generate_field_name(std::ostream& out, const t_field* field) {
  out << "\"" << field->get_name() << "=\"";
}

void generate_field(std::ostream& out, const t_field* field) {
  generate_field_name(out, field);
  generate_field_value(out, field);
}

void generate_fields(std::ostream& out,
                     const vector<t_field*>& fields,
                     const std::string& indent) {
  const vector<t_field*>::const_iterator beg = fields.begin();
  const vector<t_field*>::const_iterator end = fields.end();

  for (vector<t_field*>::const_iterator it = beg; it != end; ++it) {
    out << indent << "out << ";

    if (it != beg) {
      out << "\", \" << ";
    }

    generate_field(out, *it);
    out << ";" << endl;
  }
}
}

/**
 * Generates operator<<
 */
void t_cpp_generator::generate_struct_print_method(std::ostream& out, t_struct* tstruct) {
  out << indent();
  generate_struct_print_method_decl(out, tstruct);
  out << " {" << endl;

  indent_up();

  out << indent() << "using ::apache::thrift::to_string;" << endl;
  out << indent() << "out << \"" << tstruct->get_name() << "(\";" << endl;
  struct_ostream_operator_generator::generate_fields(out, tstruct->get_members(), indent());
  out << indent() << "out << \")\";" << endl;

  indent_down();
  out << "}" << endl << endl;
}

/**
 * Generates what() method for exceptions
 */
void t_cpp_generator::generate_exception_what_method(std::ostream& out, t_struct* tstruct) {
  out << indent();
  generate_exception_what_method_decl(out, tstruct, true);
  out << " {" << endl;

  indent_up();
  out << indent() << "try {" << endl;

  indent_up();
  out << indent() << "std::stringstream ss;" << endl;
  out << indent() << "ss << \"TException - service has thrown: \" << *this;" << endl;
  out << indent() << "this->thriftTExceptionMessageHolder_ = ss.str();" << endl;
  out << indent() << "return this->thriftTExceptionMessageHolder_.c_str();" << endl;
  indent_down();

  out << indent() << "} catch (const std::exception&) {" << endl;

  indent_up();
  out << indent() << "return \"TException - service has thrown: " << tstruct->get_name() << "\";"
      << endl;
  indent_down();

  out << indent() << "}" << endl;

  indent_down();
  out << "}" << endl << endl;
}

/**
 * Generates a thrift service. In C++, this comprises an entirely separate
 * header and source file. The header file defines the methods and includes
 * the data types defined in the main header file, and the implementation
 * file contains implementations of the basic printer and default interfaces.
 *
 * @param tservice The service definition
 */
void t_cpp_generator::generate_service(t_service* tservice) {
  string svcname = tservice->get_name();

  // Make output files
  string f_header_name = get_out_dir() + svcname + ".h";
  f_header_.open(f_header_name.c_str());

  // Print header file includes
  f_header_ << autogen_comment();
  f_header_ << "#ifndef " << svcname << "_H" << endl << "#define " << svcname << "_H" << endl
            << endl;
  if (gen_cob_style_) {
    f_header_ << "#include <thrift/transport/TBufferTransports.h>" << endl // TMemoryBuffer
              << "#include <functional>" << endl 
              << "namespace apache { namespace thrift { namespace async {" << endl
              << "class TAsyncChannel;" << endl << "}}}" << endl;
  }
  f_header_ << "#include <thrift/TDispatchProcessor.h>" << endl;
  if (gen_cob_style_) {
    f_header_ << "#include <thrift/async/TAsyncDispatchProcessor.h>" << endl;
  }
  f_header_ << "#include <thrift/async/TConcurrentClientSyncInfo.h>" << endl;
  f_header_ << "#include <memory>" << endl;
  f_header_ << "#include \"" << get_include_prefix(*get_program()) << program_name_ << "_types.h\""
            << endl;

  t_service* extends_service = tservice->get_extends();
  if (extends_service != nullptr) {
    f_header_ << "#include \"" << get_include_prefix(*(extends_service->get_program()))
              << extends_service->get_name() << ".h\"" << endl;
  }

  f_header_ << endl << ns_open_ << endl << endl;

  f_header_ << "#ifdef _MSC_VER\n"
               "  #pragma warning( push )\n"
               "  #pragma warning (disable : 4250 ) //inheriting methods via dominance \n"
               "#endif\n\n";

  // Service implementation file includes
  string f_service_name = get_out_dir() + svcname + ".cpp";
  f_service_.open(f_service_name.c_str());
  f_service_ << autogen_comment();
  f_service_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl;
  if (gen_cob_style_) {
    f_service_ << "#include \"thrift/async/TAsyncChannel.h\"" << endl;
  }
  if (gen_templates_) {
    f_service_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".tcc\""
               << endl;

    string f_service_tcc_name = get_out_dir() + svcname + ".tcc";
    f_service_tcc_.open(f_service_tcc_name.c_str());
    f_service_tcc_ << autogen_comment();
    f_service_tcc_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\""
                   << endl;

    f_service_tcc_ << "#ifndef " << svcname << "_TCC" << endl << "#define " << svcname << "_TCC"
                   << endl << endl;

    if (gen_cob_style_) {
      f_service_tcc_ << "#include \"thrift/async/TAsyncChannel.h\"" << endl;
    }
  }

  f_service_ << endl << ns_open_ << endl << endl;
  f_service_tcc_ << endl << ns_open_ << endl << endl;

  // Generate all the components
  generate_service_interface(tservice, "");
  generate_service_interface_factory(tservice, "");
  generate_service_null(tservice, "");
  generate_service_helpers(tservice);
  generate_service_client(tservice, "");
  generate_service_processor(tservice, "");
  generate_service_multiface(tservice);
  generate_service_client(tservice, "Concurrent");

  // Generate skeleton
  if (!gen_no_skeleton_) {
      generate_service_skeleton(tservice);
  }

  // Generate all the cob components
  if (gen_cob_style_) {
    generate_service_interface(tservice, "CobCl");
    generate_service_interface(tservice, "CobSv");
    generate_service_interface_factory(tservice, "CobSv");
    generate_service_null(tservice, "CobSv");
    generate_service_client(tservice, "Cob");
    generate_service_processor(tservice, "Cob");

    if (!gen_no_skeleton_) {
      generate_service_async_skeleton(tservice);
    }

  }

  f_header_ << "#ifdef _MSC_VER\n"
               "  #pragma warning( pop )\n"
               "#endif\n\n";

  // Close the namespace
  f_service_ << ns_close_ << endl << endl;
  f_service_tcc_ << ns_close_ << endl << endl;
  f_header_ << ns_close_ << endl << endl;

  // TODO(simpkins): Make this a separate option
  if (gen_templates_) {
    f_header_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".tcc\"" << endl
              << "#include \"" << get_include_prefix(*get_program()) << program_name_
              << "_types.tcc\"" << endl << endl;
  }

  f_header_ << "#endif" << endl;
  f_service_tcc_ << "#endif" << endl;

  // Close the files
  f_service_tcc_.close();
  f_service_.close();
  f_header_.close();
}

/**
 * Generates helper functions for a service. Basically, this generates types
 * for all the arguments and results to functions.
 *
 * @param tservice The service to generate a header definition for
 */
void t_cpp_generator::generate_service_helpers(t_service* tservice) {
  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;
  std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);

  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    t_struct* ts = (*f_iter)->get_arglist();
    string name_orig = ts->get_name();

    // TODO(dreiss): Why is this stuff not in generate_function_helpers?
    ts->set_name(tservice->get_name() + "_" + (*f_iter)->get_name() + "_args");
    generate_struct_declaration(f_header_, ts, false);
    generate_struct_definition(out, f_service_, ts, false);
    generate_struct_reader(out, ts);
    generate_struct_writer(out, ts);
    ts->set_name(tservice->get_name() + "_" + (*f_iter)->get_name() + "_pargs");
    generate_struct_declaration(f_header_, ts, false, true, false, true);
    generate_struct_definition(out, f_service_, ts, false);
    generate_struct_writer(out, ts, true);
    ts->set_name(name_orig);

    generate_function_helpers(tservice, *f_iter);
  }
}

/**
 * Generates a service interface definition.
 *
 * @param tservice The service to generate a header definition for
 */
void t_cpp_generator::generate_service_interface(t_service* tservice, string style) {

  string service_if_name = service_name_ + style + "If";
  if (style == "CobCl") {
    // Forward declare the client.
    string client_name = service_name_ + "CobClient";
    if (gen_templates_) {
      client_name += "T";
      service_if_name += "T";
      indent(f_header_) << "template <class Protocol_>" << endl;
    }
    indent(f_header_) << "class " << client_name << ";" << endl << endl;
  }

  string extends = "";
  if (tservice->get_extends() != nullptr) {
    extends = " : virtual public " + type_name(tservice->get_extends()) + style + "If";
    if (style == "CobCl" && gen_templates_) {
      // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
      // parent services were also generated with templates enabled.
      extends += "T<Protocol_>";
    }
  }

  if (style == "CobCl" && gen_templates_) {
    f_header_ << "template <class Protocol_>" << endl;
  }

  generate_java_doc(f_header_, tservice);

  f_header_ << "class " << service_if_name << extends << " {" << endl << " public:" << endl;
  indent_up();
  f_header_ << indent() << "virtual ~" << service_if_name << "() {}" << endl;

  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    if ((*f_iter)->has_doc())
      f_header_ << endl;
    generate_java_doc(f_header_, *f_iter);
    f_header_ << indent() << "virtual " << function_signature(*f_iter, style) << " = 0;" << endl;
  }
  indent_down();
  f_header_ << "};" << endl << endl;

  if (style == "CobCl" && gen_templates_) {
    // generate a backwards-compatible typedef for clients that do not
    // know about the new template-style code
    f_header_ << "typedef " << service_if_name << "< ::apache::thrift::protocol::TProtocol> "
              << service_name_ << style << "If;" << endl << endl;
  }
}

/**
 * Generates a service interface factory.
 *
 * @param tservice The service to generate an interface factory for.
 */
void t_cpp_generator::generate_service_interface_factory(t_service* tservice, string style) {
  string service_if_name = service_name_ + style + "If";

  // Figure out the name of the upper-most parent class.
  // Getting everything to work out properly with inheritance is annoying.
  // Here's what we're doing for now:
  //
  // - All handlers implement getHandler(), but subclasses use covariant return
  //   types to return their specific service interface class type.  We have to
  //   use raw pointers because of this; shared_ptr<> can't be used for
  //   covariant return types.
  //
  // - Since we're not using shared_ptr<>, we also provide a releaseHandler()
  //   function that must be called to release a pointer to a handler obtained
  //   via getHandler().
  //
  //   releaseHandler() always accepts a pointer to the upper-most parent class
  //   type.  This is necessary since the parent versions of releaseHandler()
  //   may accept any of the parent types, not just the most specific subclass
  //   type.  Implementations can use dynamic_cast to cast the pointer to the
  //   subclass type if desired.
  t_service* base_service = tservice;
  while (base_service->get_extends() != nullptr) {
    base_service = base_service->get_extends();
  }
  string base_if_name = type_name(base_service) + style + "If";

  // Generate the abstract factory class
  string factory_name = service_if_name + "Factory";
  string extends;
  if (tservice->get_extends() != nullptr) {
    extends = " : virtual public " + type_name(tservice->get_extends()) + style + "IfFactory";
  }

  f_header_ << "class " << factory_name << extends << " {" << endl << " public:" << endl;
  indent_up();
  f_header_ << indent() << "typedef " << service_if_name << " Handler;" << endl << endl << indent()
            << "virtual ~" << factory_name << "() {}" << endl << endl << indent() << "virtual "
            << service_if_name << "* getHandler("
            << "const ::apache::thrift::TConnectionInfo& connInfo)"
            << (extends.empty() ? "" : " override") << " = 0;" << endl << indent()
            << "virtual void releaseHandler(" << base_if_name << "* /* handler */)"
            << (extends.empty() ? "" : " override") << " = 0;" << endl << indent();

  indent_down();
  f_header_ << "};" << endl << endl;

  // Generate the singleton factory class
  string singleton_factory_name = service_if_name + "SingletonFactory";
  f_header_ << "class " << singleton_factory_name << " : virtual public " << factory_name << " {"
            << endl << " public:" << endl;
  indent_up();
  f_header_ << indent() << singleton_factory_name << "(const ::std::shared_ptr<" << service_if_name
            << ">& iface) : iface_(iface) {}" << endl << indent() << "virtual ~"
            << singleton_factory_name << "() {}" << endl << endl << indent() << "virtual "
            << service_if_name << "* getHandler("
            << "const ::apache::thrift::TConnectionInfo&) override {" << endl << indent()
            << "  return iface_.get();" << endl << indent() << "}" << endl << indent()
            << "virtual void releaseHandler(" << base_if_name << "* /* handler */) override {}" << endl;

  f_header_ << endl << " protected:" << endl << indent() << "::std::shared_ptr<" << service_if_name
            << "> iface_;" << endl;

  indent_down();
  f_header_ << "};" << endl << endl;
}

/**
 * Generates a null implementation of the service.
 *
 * @param tservice The service to generate a header definition for
 */
void t_cpp_generator::generate_service_null(t_service* tservice, string style) {
  string extends = "";
  if (tservice->get_extends() != nullptr) {
    extends = " , virtual public " + type_name(tservice->get_extends()) + style + "Null";
  }
  f_header_ << "class " << service_name_ << style << "Null : virtual public " << service_name_
            << style << "If" << extends << " {" << endl << " public:" << endl;
  indent_up();
  f_header_ << indent() << "virtual ~" << service_name_ << style << "Null() {}" << endl;
  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    f_header_ << indent() << function_signature(*f_iter, style, "", false)
              << " override {" << endl;
    indent_up();

    t_type* returntype = (*f_iter)->get_returntype();
    t_field returnfield(returntype, "_return");

    if (style == "") {
      if (returntype->is_void() || is_complex_type(returntype)) {
        f_header_ << indent() << "return;" << endl;
      } else {
        f_header_ << indent() << declare_field(&returnfield, true) << endl << indent()
                  << "return _return;" << endl;
      }
    } else if (style == "CobSv") {
      if (returntype->is_void()) {
        f_header_ << indent() << "return cob();" << endl;
      } else {
        t_field returnfield(returntype, "_return");
        f_header_ << indent() << declare_field(&returnfield, true) << endl << indent()
                  << "return cob(_return);" << endl;
      }

    } else {
      throw "UNKNOWN STYLE";
    }

    indent_down();
    f_header_ << indent() << "}" << endl;
  }
  indent_down();
  f_header_ << "};" << endl << endl;
}

void t_cpp_generator::generate_function_call(ostream& out,
                                             t_function* tfunction,
                                             string target,
                                             string iface,
                                             string arg_prefix) {
  bool first = true;
  t_type* ret_type = get_true_type(tfunction->get_returntype());
  out << indent();
  if (!tfunction->is_oneway() && !ret_type->is_void()) {
    if (is_complex_type(ret_type)) {
      first = false;
      out << iface << "->" << tfunction->get_name() << "(" << target;
    } else {
      out << target << " = " << iface << "->" << tfunction->get_name() << "(";
    }
  } else {
    out << iface << "->" << tfunction->get_name() << "(";
  }
  const std::vector<t_field*>& fields = tfunction->get_arglist()->get_members();
  vector<t_field*>::const_iterator f_iter;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    if (first) {
      first = false;
    } else {
      out << ", ";
    }
    out << arg_prefix << (*f_iter)->get_name();
  }
  out << ");" << endl;
}

void t_cpp_generator::generate_service_async_skeleton(t_service* tservice) {
  string svcname = tservice->get_name();

  // Service implementation file includes
  string f_skeleton_name = get_out_dir() + svcname + "_async_server.skeleton.cpp";

  string ns = namespace_prefix(tservice->get_program()->get_namespace("cpp"));

  ofstream_with_content_based_conditional_update f_skeleton;
  f_skeleton.open(f_skeleton_name.c_str());
  f_skeleton << "// This autogenerated skeleton file illustrates one way to adapt a synchronous"
             << endl << "// interface into an asynchronous interface. You should copy it to another"
             << endl
             << "// filename to avoid overwriting it and rewrite as asynchronous any functions"
             << endl << "// that would otherwise introduce unwanted latency." << endl << endl
             << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl
             << "#include <thrift/protocol/TBinaryProtocol.h>" << endl
             << "#include <thrift/async/TAsyncProtocolProcessor.h>" << endl
             << "#include <thrift/async/TEvhttpServer.h>" << endl
             << "#include <event.h>" << endl
             << "#include <evhttp.h>" << endl << endl
             << "using namespace ::apache::thrift;" << endl
             << "using namespace ::apache::thrift::protocol;" << endl
             << "using namespace ::apache::thrift::transport;" << endl
             << "using namespace ::apache::thrift::async;" << endl << endl;

  // the following code would not compile:
  // using namespace ;
  // using namespace ::;
  if ((!ns.empty()) && (ns.compare(" ::") != 0)) {
    f_skeleton << "using namespace " << string(ns, 0, ns.size() - 2) << ";" << endl << endl;
  }

  f_skeleton << "class " << svcname << "Handler : virtual public " << svcname << "If {" << endl
             << " public:" << endl;
  indent_up();
  f_skeleton << indent() << svcname << "Handler() {" << endl << indent()
             << "  // Your initialization goes here" << endl << indent() << "}" << endl << endl;

  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    generate_java_doc(f_skeleton, *f_iter);
    f_skeleton << indent() << function_signature(*f_iter, "") << " {" << endl << indent()
               << "  // Your implementation goes here" << endl << indent() << "  printf(\""
               << (*f_iter)->get_name() << "\\n\");" << endl << indent() << "}" << endl << endl;
  }

  indent_down();
  f_skeleton << "};" << endl << endl;

  f_skeleton << "class " << svcname << "AsyncHandler : "
             << "public " << svcname << "CobSvIf {" << endl << " public:" << endl;
  indent_up();
  f_skeleton << indent() << svcname << "AsyncHandler() {" << endl << indent()
             << "  syncHandler_ = std::unique_ptr<" << svcname << "Handler>(new " << svcname
             << "Handler);" << endl << indent() << "  // Your initialization goes here" << endl
             << indent() << "}" << endl;
  f_skeleton << indent() << "virtual ~" << service_name_ << "AsyncHandler();" << endl;

  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    f_skeleton << endl << indent() << function_signature(*f_iter, "CobSv", "", true) << " {"
               << endl;
    indent_up();

    t_type* returntype = (*f_iter)->get_returntype();
    t_field returnfield(returntype, "_return");

    string target = returntype->is_void() ? "" : "_return";
    if (!returntype->is_void()) {
      f_skeleton << indent() << declare_field(&returnfield, true) << endl;
    }
    generate_function_call(f_skeleton, *f_iter, target, "syncHandler_", "");
    f_skeleton << indent() << "return cob(" << target << ");" << endl;

    scope_down(f_skeleton);
  }
  f_skeleton << endl << " protected:" << endl << indent() << "std::unique_ptr<" << svcname
             << "Handler> syncHandler_;" << endl;
  indent_down();
  f_skeleton << "};" << endl << endl;

  f_skeleton << indent() << "int main(int argc, char **argv) {" << endl;
  indent_up();
  f_skeleton
      << indent() << "int port = 9090;" << endl << indent() << "::std::shared_ptr<" << svcname
      << "AsyncHandler> handler(new " << svcname << "AsyncHandler());" << endl << indent()
      << "::std::shared_ptr<" << svcname << "AsyncProcessor> processor(new " << svcname << "AsyncProcessor(handler));" << endl
      << indent() << "::std::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());"
      << endl
      << indent() << "::std::shared_ptr<TAsyncProtocolProcessor> protocolProcessor(new TAsyncProtocolProcessor(processor, protocolFactory));"
      << endl << endl << indent()
      << "TEvhttpServer server(protocolProcessor, port);"
      << endl << indent() << "server.serve();" << endl << indent() << "return 0;" << endl;
  indent_down();
  f_skeleton << "}" << endl << endl;
}

/**
 * Generates a multiface, which is a single server that just takes a set
 * of objects implementing the interface and calls them all, returning the
 * value of the last one to be called.
 *
 * @param tservice The service to generate a multiserver for.
 */
void t_cpp_generator::generate_service_multiface(t_service* tservice) {
  // Generate the dispatch methods
  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;

  string extends = "";
  string extends_multiface = "";
  if (tservice->get_extends() != nullptr) {
    extends = type_name(tservice->get_extends());
    extends_multiface = ", public " + extends + "Multiface";
  }

  string list_type = string("std::vector<std::shared_ptr<") + service_name_ + "If> >";

  // Generate the header portion
  f_header_ << "class " << service_name_ << "Multiface : "
            << "virtual public " << service_name_ << "If" << extends_multiface << " {" << endl
            << " public:" << endl;
  indent_up();
  f_header_ << indent() << service_name_ << "Multiface(" << list_type
            << "& ifaces) : ifaces_(ifaces) {" << endl;
  if (!extends.empty()) {
    f_header_ << indent()
              << "  std::vector<std::shared_ptr<" + service_name_ + "If> >::iterator iter;"
              << endl << indent() << "  for (iter = ifaces.begin(); iter != ifaces.end(); ++iter) {"
              << endl << indent() << "    " << extends << "Multiface::add(*iter);" << endl
              << indent() << "  }" << endl;
  }
  f_header_ << indent() << "}" << endl << indent() << "virtual ~" << service_name_
            << "Multiface() {}" << endl;
  indent_down();

  // Protected data members
  f_header_ << " protected:" << endl;
  indent_up();
  f_header_ << indent() << list_type << " ifaces_;" << endl << indent() << service_name_
            << "Multiface() {}" << endl << indent() << "void add(::std::shared_ptr<"
            << service_name_ << "If> iface) {" << endl;
  if (!extends.empty()) {
    f_header_ << indent() << "  " << extends << "Multiface::add(iface);" << endl;
  }
  f_header_ << indent() << "  ifaces_.push_back(iface);" << endl << indent() << "}" << endl;
  indent_down();

  f_header_ << indent() << " public:" << endl;
  indent_up();

  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    generate_java_doc(f_header_, *f_iter);
    t_struct* arglist = (*f_iter)->get_arglist();
    const vector<t_field*>& args = arglist->get_members();
    vector<t_field*>::const_iterator a_iter;

    string call = string("ifaces_[i]->") + (*f_iter)->get_name() + "(";
    bool first = true;
    if (is_complex_type((*f_iter)->get_returntype())) {
      call += "_return";
      first = false;
    }
    for (a_iter = args.begin(); a_iter != args.end(); ++a_iter) {
      if (first) {
        first = false;
      } else {
        call += ", ";
      }
      call += (*a_iter)->get_name();
    }
    call += ")";

    f_header_ << indent() << function_signature(*f_iter, "") << " override {" << endl;
    indent_up();
    f_header_ << indent() << "size_t sz = ifaces_.size();" << endl << indent() << "size_t i = 0;"
              << endl << indent() << "for (; i < (sz - 1); ++i) {" << endl;
    indent_up();
    f_header_ << indent() << call << ";" << endl;
    indent_down();
    f_header_ << indent() << "}" << endl;

    if (!(*f_iter)->get_returntype()->is_void()) {
      if (is_complex_type((*f_iter)->get_returntype())) {
        f_header_ << indent() << call << ";" << endl << indent() << "return;" << endl;
      } else {
        f_header_ << indent() << "return " << call << ";" << endl;
      }
    } else {
      f_header_ << indent() << call << ";" << endl;
    }

    indent_down();
    f_header_ << indent() << "}" << endl << endl;
  }

  indent_down();
  f_header_ << indent() << "};" << endl << endl;
}

/**
 * Generates a service client definition.
 *
 * @param tservice The service to generate a server for.
 */
void t_cpp_generator::generate_service_client(t_service* tservice, string style) {
  string ifstyle;
  if (style == "Cob") {
    ifstyle = "CobCl";
  }

  std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
  string template_header, template_suffix, short_suffix, protocol_type, _this;
  string const prot_factory_type = "::apache::thrift::protocol::TProtocolFactory";
  if (gen_templates_) {
    template_header = "template <class Protocol_>\n";
    short_suffix = "T";
    template_suffix = "T<Protocol_>";
    protocol_type = "Protocol_";
    _this = "this->";
  } else {
    protocol_type = "::apache::thrift::protocol::TProtocol";
  }
  string prot_ptr = "std::shared_ptr< " + protocol_type + ">";
  string client_suffix = "Client" + template_suffix;
  string if_suffix = "If";
  if (style == "Cob") {
    if_suffix += template_suffix;
  }

  string extends = "";
  string extends_client = "";
  if (tservice->get_extends() != nullptr) {
    // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
    // parent services were also generated with templates enabled.
    extends = type_name(tservice->get_extends());
    extends_client = ", public " + extends + style + client_suffix;
  }

  // Generate the header portion
  if (style == "Concurrent") {
    f_header_ << "// The \'concurrent\' client is a thread safe client that correctly handles\n"
                 "// out of order responses.  It is slower than the regular client, so should\n"
                 "// only be used when you need to share a connection among multiple threads\n";
  }
  f_header_ << template_header << "class " << service_name_ << style << "Client" << short_suffix
            << " : "
            << "virtual public " << service_name_ << ifstyle << if_suffix << extends_client << " {"
            << endl << " public:" << endl;

  indent_up();
  if (style != "Cob") {
    f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "(" << prot_ptr
		<< " prot";
	if (style == "Concurrent") {
		f_header_ << ", std::shared_ptr< ::apache::thrift::async::TConcurrentClientSyncInfo> sync";
	}
	f_header_ << ") ";

    if (extends.empty()) {
      if (style == "Concurrent") {
        f_header_ << ": sync_(sync)" << endl;
      }
      f_header_ << "{" << endl;
      f_header_ << indent() << "  setProtocol" << short_suffix << "(prot);" << endl << indent()
                << "}" << endl;
    } else {
      f_header_ << ":" << endl;
      f_header_ << indent() << "  " << extends << style << client_suffix << "(prot, prot";
      if (style == "Concurrent") {
          f_header_ << ", sync";
      }
      f_header_ << ") {}" << endl;
    }

    f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "(" << prot_ptr
		<< " iprot, " << prot_ptr << " oprot";
	if (style == "Concurrent") {
		f_header_ << ", std::shared_ptr< ::apache::thrift::async::TConcurrentClientSyncInfo> sync";
	}
	f_header_ << ") ";
	
    if (extends.empty()) {
      if (style == "Concurrent") {
        f_header_ << ": sync_(sync)" << endl;
      }
      f_header_ << "{" << endl;
      f_header_ << indent() << "  setProtocol" << short_suffix << "(iprot,oprot);" << endl
                << indent() << "}" << endl;
    } else {
      f_header_ << ":" << indent() << "  " << extends << style << client_suffix
                << "(iprot, oprot";
      if (style == "Concurrent") {
          f_header_ << ", sync";
      }
      f_header_ << ") {}" << endl;
    }

    // create the setProtocol methods
    if (extends.empty()) {
      f_header_ << " private:" << endl;
      // 1: one parameter
      f_header_ << indent() << "void setProtocol" << short_suffix << "(" << prot_ptr << " prot) {"
                << endl;
      f_header_ << indent() << "setProtocol" << short_suffix << "(prot,prot);" << endl;
      f_header_ << indent() << "}" << endl;
      // 2: two parameter
      f_header_ << indent() << "void setProtocol" << short_suffix << "(" << prot_ptr << " iprot, "
                << prot_ptr << " oprot) {" << endl;

      f_header_ << indent() << "  piprot_=iprot;" << endl << indent() << "  poprot_=oprot;" << endl
                << indent() << "  iprot_ = iprot.get();" << endl << indent()
                << "  oprot_ = oprot.get();" << endl;

      f_header_ << indent() << "}" << endl;
      f_header_ << " public:" << endl;
    }

    // Generate getters for the protocols.
    // Note that these are not currently templated for simplicity.
    // TODO(simpkins): should they be templated?
    f_header_ << indent()
              << "std::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() {"
              << endl << indent() << "  return " << _this << "piprot_;" << endl << indent() << "}"
              << endl;

    f_header_ << indent()
              << "std::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() {"
              << endl << indent() << "  return " << _this << "poprot_;" << endl << indent() << "}"
              << endl;

  } else /* if (style == "Cob") */ {
    f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "("
              << "std::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel, "
              << "::apache::thrift::protocol::TProtocolFactory* protocolFactory) :" << endl;
    if (extends.empty()) {
      f_header_ << indent() << "  channel_(channel)," << endl << indent()
                << "  itrans_(new ::apache::thrift::transport::TMemoryBuffer())," << endl
                << indent() << "  otrans_(new ::apache::thrift::transport::TMemoryBuffer()),"
                << endl;
      if (gen_templates_) {
        // TProtocolFactory classes return generic TProtocol pointers.
        // We have to dynamic cast to the Protocol_ type we are expecting.
        f_header_ << indent() << "  piprot_(::std::dynamic_pointer_cast<Protocol_>("
                  << "protocolFactory->getProtocol(itrans_)))," << endl << indent()
                  << "  poprot_(::std::dynamic_pointer_cast<Protocol_>("
                  << "protocolFactory->getProtocol(otrans_))) {" << endl;
        // Throw a TException if either dynamic cast failed.
        f_header_ << indent() << "  if (!piprot_ || !poprot_) {" << endl << indent()
                  << "    throw ::apache::thrift::TException(\""
                  << "TProtocolFactory returned unexpected protocol type in " << service_name_
                  << style << "Client" << short_suffix << " constructor\");" << endl << indent()
                  << "  }" << endl;
      } else {
        f_header_ << indent() << "  piprot_(protocolFactory->getProtocol(itrans_))," << endl
                  << indent() << "  poprot_(protocolFactory->getProtocol(otrans_)) {" << endl;
      }
      f_header_ << indent() << "  iprot_ = piprot_.get();" << endl << indent()
                << "  oprot_ = poprot_.get();" << endl << indent() << "}" << endl;
    } else {
      f_header_ << indent() << "  " << extends << style << client_suffix
                << "(channel, protocolFactory) {}" << endl;
    }
  }

  if (style == "Cob") {
    generate_java_doc(f_header_, tservice);

    f_header_ << indent()
              << "::std::shared_ptr< ::apache::thrift::async::TAsyncChannel> getChannel() {" << endl
              << indent() << "  return " << _this << "channel_;" << endl << indent() << "}" << endl;
    if (!gen_no_client_completion_) {
      f_header_ << indent() << "virtual void completed__(bool /* success */) {}" << endl;
    }
  }

  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::const_iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    generate_java_doc(f_header_, *f_iter);
    indent(f_header_) << function_signature(*f_iter, ifstyle) 
                      << " override;" << endl;
    // TODO(dreiss): Use private inheritance to avoid generating thise in cob-style.
    if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
      // concurrent clients need to move the seqid from the send function to the
      // recv function.  Oneway methods don't have a recv function, so we don't need to
      // move the seqid for them.  Attempting to do so would result in a seqid leak.
      t_function send_function(g_type_i32, /*returning seqid*/
                               string("send_") + (*f_iter)->get_name(),
                               (*f_iter)->get_arglist());
      indent(f_header_) << function_signature(&send_function, "") << ";" << endl;
    } else {
      t_function send_function(g_type_void,
                               string("send_") + (*f_iter)->get_name(),
                               (*f_iter)->get_arglist());
      indent(f_header_) << function_signature(&send_function, "") << ";" << endl;
    }
    if (!(*f_iter)->is_oneway()) {
      if (style == "Concurrent") {
        t_field seqIdArg(g_type_i32, "seqid");
        t_struct seqIdArgStruct(program_);
        seqIdArgStruct.append(&seqIdArg);
        t_function recv_function((*f_iter)->get_returntype(),
                                 string("recv_") + (*f_iter)->get_name(),
                                 &seqIdArgStruct);
        indent(f_header_) << function_signature(&recv_function, "") << ";" << endl;
      } else {
        t_struct noargs(program_);
        t_function recv_function((*f_iter)->get_returntype(),
                                 string("recv_") + (*f_iter)->get_name(),
                                 &noargs);
        indent(f_header_) << function_signature(&recv_function, "") << ";" << endl;
      }
    }
  }
  indent_down();

  if (extends.empty()) {
    f_header_ << " protected:" << endl;
    indent_up();

    if (style == "Cob") {
      f_header_ << indent()
                << "::std::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel_;" << endl
                << indent()
                << "::std::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> itrans_;" << endl
                << indent()
                << "::std::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> otrans_;"
                << endl;
    }
    f_header_ <<
      indent() << prot_ptr << " piprot_;" << endl <<
      indent() << prot_ptr << " poprot_;" << endl <<
      indent() << protocol_type << "* iprot_;" << endl <<
      indent() << protocol_type << "* oprot_;" << endl;

    if (style == "Concurrent") {
      f_header_ <<
        indent() << "std::shared_ptr< ::apache::thrift::async::TConcurrentClientSyncInfo> sync_;"<<endl;
    }
    indent_down();
  }

  f_header_ << "};" << endl << endl;

  if (gen_templates_) {
    // Output a backwards compatibility typedef using
    // TProtocol as the template parameter.
    f_header_ << "typedef " << service_name_ << style
              << "ClientT< ::apache::thrift::protocol::TProtocol> " << service_name_ << style
              << "Client;" << endl << endl;
  }

  string scope = service_name_ + style + client_suffix + "::";

  // Generate client method implementations
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    string seqIdCapture;
    string seqIdUse;
    string seqIdCommaUse;
    if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
      seqIdCapture = "int32_t seqid = ";
      seqIdUse = "seqid";
      seqIdCommaUse = ", seqid";
    }

    string funname = (*f_iter)->get_name();

    // Open function
    if (gen_templates_) {
      indent(out) << template_header;
    }
    indent(out) << function_signature(*f_iter, ifstyle, scope) << endl;
    scope_up(out);
    indent(out) << seqIdCapture << "send_" << funname << "(";

    // Get the struct of function call params
    t_struct* arg_struct = (*f_iter)->get_arglist();

    // Declare the function arguments
    const vector<t_field*>& fields = arg_struct->get_members();
    vector<t_field*>::const_iterator fld_iter;
    bool first = true;
    for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
      if (first) {
        first = false;
      } else {
        out << ", ";
      }
      out << (*fld_iter)->get_name();
    }
    out << ");" << endl;

    if (style != "Cob") {
      if (!(*f_iter)->is_oneway()) {
        out << indent();
        if (!(*f_iter)->get_returntype()->is_void()) {
          if (is_complex_type((*f_iter)->get_returntype())) {
            out << "recv_" << funname << "(_return" << seqIdCommaUse << ");" << endl;
          } else {
            out << "return recv_" << funname << "(" << seqIdUse << ");" << endl;
          }
        } else {
          out << "recv_" << funname << "(" << seqIdUse << ");" << endl;
        }
      }
    } else {
      if (!(*f_iter)->is_oneway()) {
        out << indent() << _this << "channel_->sendAndRecvMessage("
            << "::std::bind(cob, this), " << _this << "otrans_.get(), " << _this << "itrans_.get());"
            << endl;
      } else {
        out << indent() << _this << "channel_->sendMessage("
            << "::std::bind(cob, this), " << _this << "otrans_.get());" << endl;
      }
    }
    scope_down(out);
    out << endl;

    // if (style != "Cob") // TODO(dreiss): Libify the client and don't generate this for cob-style
    if (true) {
      t_type* send_func_return_type = g_type_void;
      if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
        send_func_return_type = g_type_i32;
      }
      // Function for sending
      t_function send_function(send_func_return_type,
                               string("send_") + (*f_iter)->get_name(),
                               (*f_iter)->get_arglist());

      // Open the send function
      if (gen_templates_) {
        indent(out) << template_header;
      }
      indent(out) << function_signature(&send_function, "", scope) << endl;
      scope_up(out);

      // Function arguments and results
      string argsname = tservice->get_name() + "_" + (*f_iter)->get_name() + "_pargs";
      string resultname = tservice->get_name() + "_" + (*f_iter)->get_name() + "_presult";

      string cseqidVal = "0";
      if (style == "Concurrent") {
        if (!(*f_iter)->is_oneway()) {
          cseqidVal = "this->sync_->generateSeqId()";
        }
      }
      // Serialize the request
      out <<
        indent() << "int32_t cseqid = " << cseqidVal << ";" << endl;
      if(style == "Concurrent") {
        out <<
          indent() << "::apache::thrift::async::TConcurrentSendSentry sentry(this->sync_.get());" << endl;
      }
      if (style == "Cob") {
        out <<
          indent() << _this << "otrans_->resetBuffer();" << endl;
      }
      out <<
        indent() << _this << "oprot_->writeMessageBegin(\"" <<
        (*f_iter)->get_name() <<
        "\", ::apache::thrift::protocol::" << ((*f_iter)->is_oneway() ? "T_ONEWAY" : "T_CALL") <<
        ", cseqid);" << endl << endl <<
        indent() << argsname << " args;" << endl;

      for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
        out << indent() << "args." << (*fld_iter)->get_name() << " = &" << (*fld_iter)->get_name()
            << ";" << endl;
      }

      out << indent() << "args.write(" << _this << "oprot_);" << endl << endl << indent() << _this
          << "oprot_->writeMessageEnd();" << endl << indent() << _this
          << "oprot_->getTransport()->writeEnd();" << endl << indent() << _this
          << "oprot_->getTransport()->flush();" << endl;

      if (style == "Concurrent") {
        out << endl << indent() << "sentry.commit();" << endl;

        if (!(*f_iter)->is_oneway()) {
          out << indent() << "return cseqid;" << endl;
        }
      }
      scope_down(out);
      out << endl;

      // Generate recv function only if not an oneway function
      if (!(*f_iter)->is_oneway()) {
        t_struct noargs(program_);

        t_field seqIdArg(g_type_i32, "seqid");
        t_struct seqIdArgStruct(program_);
        seqIdArgStruct.append(&seqIdArg);

        t_struct* recv_function_args = &noargs;
        if (style == "Concurrent") {
          recv_function_args = &seqIdArgStruct;
        }

        t_function recv_function((*f_iter)->get_returntype(),
                                 string("recv_") + (*f_iter)->get_name(),
                                 recv_function_args);
        // Open the recv function
        if (gen_templates_) {
          indent(out) << template_header;
        }
        indent(out) << function_signature(&recv_function, "", scope) << endl;
        scope_up(out);

        out << endl <<
          indent() << "int32_t rseqid = 0;" << endl <<
          indent() << "std::string fname;" << endl <<
          indent() << "::apache::thrift::protocol::TMessageType mtype;" << endl;
        if(style == "Concurrent") {
          out <<
            endl <<
            indent() << "// the read mutex gets dropped and reacquired as part of waitForWork()" << endl <<
            indent() << "// The destructor of this sentry wakes up other clients" << endl <<
            indent() << "::apache::thrift::async::TConcurrentRecvSentry sentry(this->sync_.get(), seqid);" << endl;
        }
        if (style == "Cob" && !gen_no_client_completion_) {
          out << indent() << "bool completed = false;" << endl << endl << indent() << "try {";
          indent_up();
        }
        out << endl;
        if (style == "Concurrent") {
          out <<
            indent() << "while(true) {" << endl <<
            indent() << "  if(!this->sync_->getPending(fname, mtype, rseqid)) {" << endl;
          indent_up();
          indent_up();
        }
        out <<
          indent() << _this << "iprot_->readMessageBegin(fname, mtype, rseqid);" << endl;
        if (style == "Concurrent") {
          scope_down(out);
          out << indent() << "if(seqid == rseqid) {" << endl;
          indent_up();
        }
        out <<
          indent() << "if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {" << endl <<
          indent() << "  ::apache::thrift::TApplicationException x;" << endl <<
          indent() << "  x.read(" << _this << "iprot_);" << endl <<
          indent() << "  " << _this << "iprot_->readMessageEnd();" << endl <<
          indent() << "  " << _this << "iprot_->getTransport()->readEnd();" << endl;
        if (style == "Cob" && !gen_no_client_completion_) {
          out << indent() << "  completed = true;" << endl << indent() << "  completed__(true);"
              << endl;
        }
        if (style == "Concurrent") {
          out << indent() << "  sentry.commit();" << endl;
        }
        out <<
          indent() << "  throw x;" << endl <<
          indent() << "}" << endl <<
          indent() << "if (mtype != ::apache::thrift::protocol::T_REPLY) {" << endl <<
          indent() << "  " << _this << "iprot_->skip(" << "::apache::thrift::protocol::T_STRUCT);" << endl <<
          indent() << "  " << _this << "iprot_->readMessageEnd();" << endl <<
          indent() << "  " << _this << "iprot_->getTransport()->readEnd();" << endl;
        if (style == "Cob" && !gen_no_client_completion_) {
          out << indent() << "  completed = true;" << endl << indent() << "  completed__(false);"
              << endl;
        }
        out <<
          indent() << "}" << endl <<
          indent() << "if (fname.compare(\"" << (*f_iter)->get_name() << "\") != 0) {" << endl <<
          indent() << "  " << _this << "iprot_->skip(" << "::apache::thrift::protocol::T_STRUCT);" << endl <<
          indent() << "  " << _this << "iprot_->readMessageEnd();" << endl <<
          indent() << "  " << _this << "iprot_->getTransport()->readEnd();" << endl;
        if (style == "Cob" && !gen_no_client_completion_) {
          out << indent() << "  completed = true;" << endl << indent() << "  completed__(false);"
              << endl;
        }
        if (style == "Concurrent") {
          out << endl <<
            indent() << "  // in a bad state, don't commit" << endl <<
            indent() << "  using ::apache::thrift::protocol::TProtocolException;" << endl <<
            indent() << "  throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
        }
        out << indent() << "}" << endl;

        if (!(*f_iter)->get_returntype()->is_void()
            && !is_complex_type((*f_iter)->get_returntype())) {
          t_field returnfield((*f_iter)->get_returntype(), "_return");
          out << indent() << declare_field(&returnfield) << endl;
        }

        out << indent() << resultname << " result;" << endl;

        if (!(*f_iter)->get_returntype()->is_void()) {
          out << indent() << "result.success = &_return;" << endl;
        }

        out << indent() << "result.read(" << _this << "iprot_);" << endl << indent() << _this
            << "iprot_->readMessageEnd();" << endl << indent() << _this
            << "iprot_->getTransport()->readEnd();" << endl << endl;

        // Careful, only look for _result if not a void function
        if (!(*f_iter)->get_returntype()->is_void()) {
          if (is_complex_type((*f_iter)->get_returntype())) {
            out <<
              indent() << "if (result.__isset.success) {" << endl;
            out <<
              indent() << "  // _return pointer has now been filled" << endl;
            if (style == "Cob" && !gen_no_client_completion_) {
              out << indent() << "  completed = true;" << endl << indent() << "  completed__(true);"
                  << endl;
            }
            if (style == "Concurrent") {
              out << indent() << "  sentry.commit();" << endl;
            }
            out <<
              indent() << "  return;" << endl <<
              indent() << "}" << endl;
          } else {
            out << indent() << "if (result.__isset.success) {" << endl;
            if (style == "Cob" && !gen_no_client_completion_) {
              out << indent() << "  completed = true;" << endl << indent() << "  completed__(true);"
                  << endl;
            }
            if (style == "Concurrent") {
              out << indent() << "  sentry.commit();" << endl;
            }
            out << indent() << "  return _return;" << endl << indent() << "}" << endl;
          }
        }

        t_struct* xs = (*f_iter)->get_xceptions();
        const std::vector<t_field*>& xceptions = xs->get_members();
        vector<t_field*>::const_iterator x_iter;
        for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
          out << indent() << "if (result.__isset." << (*x_iter)->get_name() << ") {" << endl;
          if (style == "Cob" && !gen_no_client_completion_) {
            out << indent() << "  completed = true;" << endl << indent() << "  completed__(true);"
                << endl;
          }
          if (style == "Concurrent") {
            out << indent() << "  sentry.commit();" << endl;
          }
          out << indent() << "  throw result." << (*x_iter)->get_name() << ";" << endl << indent()
              << "}" << endl;
        }

        // We only get here if we are a void function
        if ((*f_iter)->get_returntype()->is_void()) {
          if (style == "Cob" && !gen_no_client_completion_) {
            out << indent() << "completed = true;" << endl << indent() << "completed__(true);"
                << endl;
          }
          if (style == "Concurrent") {
            out << indent() << "sentry.commit();" << endl;
          }
          indent(out) << "return;" << endl;
        } else {
          if (style == "Cob" && !gen_no_client_completion_) {
            out << indent() << "completed = true;" << endl << indent() << "completed__(true);"
                << endl;
          }
          if (style == "Concurrent") {
            out << indent() << "// in a bad state, don't commit" << endl;
          }
          out << indent() << "throw "
                             "::apache::thrift::TApplicationException(::apache::thrift::"
                             "TApplicationException::MISSING_RESULT, \"" << (*f_iter)->get_name()
              << " failed: unknown result\");" << endl;
        }
        if (style == "Concurrent") {
          indent_down();
          indent_down();
          out <<
            indent() << "  }" << endl <<
            indent() << "  // seqid != rseqid" << endl <<
            indent() << "  this->sync_->updatePending(fname, mtype, rseqid);" << endl <<
            endl <<
            indent() << "  // this will temporarily unlock the readMutex, and let other clients get work done" << endl <<
            indent() << "  this->sync_->waitForWork(seqid);" << endl <<
            indent() << "} // end while(true)" << endl;
        }
        if (style == "Cob" && !gen_no_client_completion_) {
          indent_down();
          out << indent() << "} catch (...) {" << endl << indent() << "  if (!completed) {" << endl
              << indent() << "    completed__(false);" << endl << indent() << "  }" << endl
              << indent() << "  throw;" << endl << indent() << "}" << endl;
        }
        // Close function
        scope_down(out);
        out << endl;
      }
    }
  }
}

class ProcessorGenerator {
public:
  ProcessorGenerator(t_cpp_generator* generator, t_service* service, const string& style);

  void run() {
    generate_class_definition();

    // Generate the dispatchCall() function
    generate_dispatch_call(false);
    if (generator_->gen_templates_) {
      generate_dispatch_call(true);
    }

    // Generate all of the process subfunctions
    generate_process_functions();

    generate_factory();
  }

  void generate_class_definition();
  void generate_dispatch_call(bool template_protocol);
  void generate_process_functions();
  void generate_factory();

protected:
  std::string type_name(t_type* ttype, bool in_typedef = false, bool arg = false) {
    return generator_->type_name(ttype, in_typedef, arg);
  }

  std::string indent() { return generator_->indent(); }
  std::ostream& indent(std::ostream& os) { return generator_->indent(os); }

  void indent_up() { generator_->indent_up(); }
  void indent_down() { generator_->indent_down(); }

  t_cpp_generator* generator_;
  t_service* service_;
  std::ostream& f_header_;
  std::ostream& f_out_;
  string service_name_;
  string style_;
  string pstyle_;
  string class_name_;
  string if_name_;
  string factory_class_name_;
  string finish_cob_;
  string finish_cob_decl_;
  string ret_type_;
  string call_context_;
  string cob_arg_;
  string call_context_arg_;
  string call_context_decl_;
  string template_header_;
  string template_suffix_;
  string typename_str_;
  string class_suffix_;
  string extends_;
};

ProcessorGenerator::ProcessorGenerator(t_cpp_generator* generator,
                                       t_service* service,
                                       const string& style)
  : generator_(generator),
    service_(service),
    f_header_(generator->f_header_),
    f_out_(generator->gen_templates_ ? generator->f_service_tcc_ : generator->f_service_),
    service_name_(generator->service_name_),
    style_(style) {
  if (style_ == "Cob") {
    pstyle_ = "Async";
    class_name_ = service_name_ + pstyle_ + "Processor";
    if_name_ = service_name_ + "CobSvIf";

    finish_cob_ = "::std::function<void(bool ok)> cob, ";
    finish_cob_decl_ = "::std::function<void(bool ok)>, ";
    cob_arg_ = "cob, ";
    ret_type_ = "void ";
  } else {
    class_name_ = service_name_ + "Processor";
    if_name_ = service_name_ + "If";

    ret_type_ = "bool ";
    // TODO(edhall) callContext should eventually be added to TAsyncProcessor
    call_context_ = ", void* callContext";
    call_context_arg_ = ", callContext";
    call_context_decl_ = ", void*";
  }

  factory_class_name_ = class_name_ + "Factory";

  if (generator->gen_templates_) {
    template_header_ = "template <class Protocol_>\n";
    template_suffix_ = "<Protocol_>";
    typename_str_ = "typename ";
    class_name_ += "T";
    factory_class_name_ += "T";
  }

  if (service_->get_extends() != nullptr) {
    extends_ = type_name(service_->get_extends()) + pstyle_ + "Processor";
    if (generator_->gen_templates_) {
      // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
      // parent services were also generated with templates enabled.
      extends_ += "T<Protocol_>";
    }
  }
}

void ProcessorGenerator::generate_class_definition() {
  // Generate the dispatch methods
  vector<t_function*> functions = service_->get_functions();
  vector<t_function*>::iterator f_iter;

  string parent_class;
  if (service_->get_extends() != nullptr) {
    parent_class = extends_;
  } else {
    if (style_ == "Cob") {
      parent_class = "::apache::thrift::async::TAsyncDispatchProcessor";
    } else {
      parent_class = "::apache::thrift::TDispatchProcessor";
    }

    if (generator_->gen_templates_) {
      parent_class += "T<Protocol_>";
    }
  }

  // Generate the header portion
  f_header_ << template_header_ << "class " << class_name_ << " : public " << parent_class << " {"
            << endl;

  // Protected data members
  f_header_ << " protected:" << endl;
  indent_up();
  f_header_ << indent() << "::std::shared_ptr<" << if_name_ << "> iface_;" << endl;
  f_header_ << indent() << "virtual " << ret_type_ << "dispatchCall(" << finish_cob_
            << "::apache::thrift::protocol::TProtocol* iprot, "
            << "::apache::thrift::protocol::TProtocol* oprot, "
            << "const std::string& fname, int32_t seqid" << call_context_ 
            << ") override;" << endl;
  if (generator_->gen_templates_) {
    f_header_ << indent() << "virtual " << ret_type_ << "dispatchCallTemplated(" << finish_cob_
              << "Protocol_* iprot, Protocol_* oprot, "
              << "const std::string& fname, int32_t seqid" << call_context_ << ");" << endl;
  }
  indent_down();

  // Process function declarations
  f_header_ << " private:" << endl;
  indent_up();

  // Declare processMap_
  f_header_ << indent() << "typedef  void (" << class_name_ << "::*"
            << "ProcessFunction)(" << finish_cob_decl_ << "int32_t, "
            << "::apache::thrift::protocol::TProtocol*, "
            << "::apache::thrift::protocol::TProtocol*" << call_context_decl_ << ");" << endl;
  if (generator_->gen_templates_) {
    f_header_ << indent() << "typedef void (" << class_name_ << "::*"
              << "SpecializedProcessFunction)(" << finish_cob_decl_ << "int32_t, "
              << "Protocol_*, Protocol_*" << call_context_decl_ << ");" << endl << indent()
              << "struct ProcessFunctions {" << endl << indent() << "  ProcessFunction generic;"
              << endl << indent() << "  SpecializedProcessFunction specialized;" << endl << indent()
              << "  ProcessFunctions(ProcessFunction g, "
              << "SpecializedProcessFunction s) :" << endl << indent() << "    generic(g)," << endl
              << indent() << "    specialized(s) {}" << endl << indent()
              << "  ProcessFunctions() : generic(nullptr), specialized(nullptr) "
              << "{}" << endl << indent() << "};" << endl << indent()
              << "typedef std::map<std::string, ProcessFunctions> "
              << "ProcessMap;" << endl;
  } else {
    f_header_ << indent() << "typedef std::map<std::string, ProcessFunction> "
              << "ProcessMap;" << endl;
  }
  f_header_ << indent() << "ProcessMap processMap_;" << endl;

  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    indent(f_header_) << "void process_" << (*f_iter)->get_name() << "(" << finish_cob_
                      << "int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, "
                         "::apache::thrift::protocol::TProtocol* oprot" << call_context_ << ");"
                      << endl;
    if (generator_->gen_templates_) {
      indent(f_header_) << "void process_" << (*f_iter)->get_name() << "(" << finish_cob_
                        << "int32_t seqid, Protocol_* iprot, Protocol_* oprot" << call_context_
                        << ");" << endl;
    }
    if (style_ == "Cob") {
      // XXX Factor this out, even if it is a pain.
      string ret_arg = ((*f_iter)->get_returntype()->is_void()
                            ? ""
                            : ", const " + type_name((*f_iter)->get_returntype()) + "& _return");
      f_header_ << indent() << "void return_" << (*f_iter)->get_name()
                << "(::std::function<void(bool ok)> cob, int32_t seqid, "
                << "::apache::thrift::protocol::TProtocol* oprot, "
                << "void* ctx" << ret_arg << ");" << endl;
      if (generator_->gen_templates_) {
        f_header_ << indent() << "void return_" << (*f_iter)->get_name()
                  << "(::std::function<void(bool ok)> cob, int32_t seqid, "
                  << "Protocol_* oprot, void* ctx" << ret_arg << ");" << endl;
      }
      // XXX Don't declare throw if it doesn't exist
      f_header_ << indent() << "void throw_" << (*f_iter)->get_name()
                << "(::std::function<void(bool ok)> cob, int32_t seqid, "
                << "::apache::thrift::protocol::TProtocol* oprot, void* ctx, "
                << "::apache::thrift::TDelayedException* _throw);" << endl;
      if (generator_->gen_templates_) {
        f_header_ << indent() << "void throw_" << (*f_iter)->get_name()
                  << "(::std::function<void(bool ok)> cob, int32_t seqid, "
                  << "Protocol_* oprot, void* ctx, "
                  << "::apache::thrift::TDelayedException* _throw);" << endl;
      }
    }
  }

  f_header_ << " public:" << endl << indent() << class_name_ << "(::std::shared_ptr<" << if_name_
            << "> iface) :" << endl;
  if (!extends_.empty()) {
    f_header_ << indent() << "  " << extends_ << "(iface)," << endl;
  }
  f_header_ << indent() << "  iface_(iface) {" << endl;
  indent_up();

  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    f_header_ << indent() << "processMap_[\"" << (*f_iter)->get_name() << "\"] = ";
    if (generator_->gen_templates_) {
      f_header_ << "ProcessFunctions(" << endl;
      if (generator_->gen_templates_only_) {
        indent(f_header_) << "  nullptr," << endl;
      } else {
        indent(f_header_) << "  &" << class_name_ << "::process_" << (*f_iter)->get_name() << ","
                          << endl;
      }
      indent(f_header_) << "  &" << class_name_ << "::process_" << (*f_iter)->get_name() << ")";
    } else {
      f_header_ << "&" << class_name_ << "::process_" << (*f_iter)->get_name();
    }
    f_header_ << ";" << endl;
  }

  indent_down();
  f_header_ << indent() << "}" << endl << endl << indent() << "virtual ~" << class_name_ << "() {}"
            << endl;
  indent_down();
  f_header_ << "};" << endl << endl;

  if (generator_->gen_templates_) {
    // Generate a backwards compatible typedef, for callers who don't know
    // about the new template-style code.
    //
    // We can't use TProtocol as the template parameter, since ProcessorT
    // provides overloaded versions of most methods, one of which accepts
    // TProtocol pointers, and one which accepts Protocol_ pointers.  This
    // results in a compile error if instantiated with Protocol_ == TProtocol.
    // Therefore, we define TDummyProtocol solely so we can use it as the
    // template parameter here.
    f_header_ << "typedef " << class_name_ << "< ::apache::thrift::protocol::TDummyProtocol > "
              << service_name_ << pstyle_ << "Processor;" << endl << endl;
  }
}

void ProcessorGenerator::generate_dispatch_call(bool template_protocol) {
  string protocol = "::apache::thrift::protocol::TProtocol";
  string function_suffix;
  if (template_protocol) {
    protocol = "Protocol_";
    // We call the generic version dispatchCall(), and the specialized
    // version dispatchCallTemplated().  We can't call them both
    // dispatchCall(), since this will cause the compiler to issue a warning if
    // a service that doesn't use templates inherits from a service that does
    // use templates: the compiler complains that the subclass only implements
    // the generic version of dispatchCall(), and hides the templated version.
    // Using different names for the two functions prevents this.
    function_suffix = "Templated";
  }

  f_out_ << template_header_ << ret_type_ << class_name_ << template_suffix_ << "::dispatchCall"
         << function_suffix << "(" << finish_cob_ << protocol << "* iprot, " << protocol
         << "* oprot, "
         << "const std::string& fname, int32_t seqid" << call_context_ << ") {" << endl;
  indent_up();

  // HOT: member function pointer map
  f_out_ << indent() << typename_str_ << "ProcessMap::iterator pfn;" << endl << indent()
         << "pfn = processMap_.find(fname);" << endl << indent()
         << "if (pfn == processMap_.end()) {" << endl;
  if (extends_.empty()) {
    f_out_ << indent() << "  iprot->skip(::apache::thrift::protocol::T_STRUCT);" << endl << indent()
           << "  iprot->readMessageEnd();" << endl << indent()
           << "  iprot->getTransport()->readEnd();" << endl << indent()
           << "  ::apache::thrift::TApplicationException "
              "x(::apache::thrift::TApplicationException::UNKNOWN_METHOD, \"Invalid method name: "
              "'\"+fname+\"'\");" << endl << indent()
           << "  oprot->writeMessageBegin(fname, ::apache::thrift::protocol::T_EXCEPTION, seqid);"
           << endl << indent() << "  x.write(oprot);" << endl << indent()
           << "  oprot->writeMessageEnd();" << endl << indent()
           << "  oprot->getTransport()->writeEnd();" << endl << indent()
           << "  oprot->getTransport()->flush();" << endl << indent()
           << (style_ == "Cob" ? "  return cob(true);" : "  return true;") << endl;
  } else {
    f_out_ << indent() << "  return " << extends_ << "::dispatchCall("
           << (style_ == "Cob" ? "cob, " : "") << "iprot, oprot, fname, seqid" << call_context_arg_
           << ");" << endl;
  }
  f_out_ << indent() << "}" << endl;
  if (template_protocol) {
    f_out_ << indent() << "(this->*(pfn->second.specialized))";
  } else {
    if (generator_->gen_templates_only_) {
      // TODO: This is a null pointer, so nothing good will come from calling
      // it.  Throw an exception instead.
      f_out_ << indent() << "(this->*(pfn->second.generic))";
    } else if (generator_->gen_templates_) {
      f_out_ << indent() << "(this->*(pfn->second.generic))";
    } else {
      f_out_ << indent() << "(this->*(pfn->second))";
    }
  }
  f_out_ << "(" << cob_arg_ << "seqid, iprot, oprot" << call_context_arg_ << ");" << endl;

  // TODO(dreiss): return pfn ret?
  if (style_ == "Cob") {
    f_out_ << indent() << "return;" << endl;
  } else {
    f_out_ << indent() << "return true;" << endl;
  }

  indent_down();
  f_out_ << "}" << endl << endl;
}

void ProcessorGenerator::generate_process_functions() {
  vector<t_function*> functions = service_->get_functions();
  vector<t_function*>::iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    if (generator_->gen_templates_) {
      generator_->generate_process_function(service_, *f_iter, style_, false);
      generator_->generate_process_function(service_, *f_iter, style_, true);
    } else {
      generator_->generate_process_function(service_, *f_iter, style_, false);
    }
  }
}

void ProcessorGenerator::generate_factory() {
  string if_factory_name = if_name_ + "Factory";

  // Generate the factory class definition
  f_header_ << template_header_ << "class " << factory_class_name_ << " : public ::apache::thrift::"
            << (style_ == "Cob" ? "async::TAsyncProcessorFactory" : "TProcessorFactory") << " {"
            << endl << " public:" << endl;
  indent_up();

  f_header_ << indent() << factory_class_name_ << "(const ::std::shared_ptr< " << if_factory_name
            << " >& handlerFactory) noexcept :" << endl << indent()
            << "    handlerFactory_(handlerFactory) {}" << endl << endl << indent()
            << "::std::shared_ptr< ::apache::thrift::"
            << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
            << "getProcessor(const ::apache::thrift::TConnectionInfo& connInfo) override;"
            << endl;

  f_header_ << endl << " protected:" << endl << indent() << "::std::shared_ptr< "
            << if_factory_name << " > handlerFactory_;" << endl;

  indent_down();
  f_header_ << "};" << endl << endl;

  // If we are generating templates, output a typedef for the plain
  // factory name.
  if (generator_->gen_templates_) {
    f_header_ << "typedef " << factory_class_name_
              << "< ::apache::thrift::protocol::TDummyProtocol > " << service_name_ << pstyle_
              << "ProcessorFactory;" << endl << endl;
  }

  // Generate the getProcessor() method
  f_out_ << template_header_ << indent() << "::std::shared_ptr< ::apache::thrift::"
         << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
         << factory_class_name_ << template_suffix_ << "::getProcessor("
         << "const ::apache::thrift::TConnectionInfo& connInfo) {" << endl;
  indent_up();

  f_out_ << indent() << "::apache::thrift::ReleaseHandler< " << if_factory_name
         << " > cleanup(handlerFactory_);" << endl << indent() << "::std::shared_ptr< "
         << if_name_ << " > handler("
         << "handlerFactory_->getHandler(connInfo), cleanup);" << endl << indent()
         << "::std::shared_ptr< ::apache::thrift::"
         << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
         << "processor(new " << class_name_ << template_suffix_ << "(handler));" << endl << indent()
         << "return processor;" << endl;

  indent_down();
  f_out_ << indent() << "}" << endl << endl;
}

/**
 * Generates a service processor definition.
 *
 * @param tservice The service to generate a processor for.
 */
void t_cpp_generator::generate_service_processor(t_service* tservice, string style) {
  ProcessorGenerator generator(this, tservice, style);
  generator.run();
}

/**
 * Generates a struct and helpers for a function.
 *
 * @param tfunction The function
 */
void t_cpp_generator::generate_function_helpers(t_service* tservice, t_function* tfunction) {
  if (tfunction->is_oneway()) {
    return;
  }

  std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);

  t_struct result(program_, tservice->get_name() + "_" + tfunction->get_name() + "_result");
  t_field success(tfunction->get_returntype(), "success", 0);
  if (!tfunction->get_returntype()->is_void()) {
    result.append(&success);
  }

  t_struct* xs = tfunction->get_xceptions();
  const vector<t_field*>& fields = xs->get_members();
  vector<t_field*>::const_iterator f_iter;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    result.append(*f_iter);
  }

  generate_struct_declaration(f_header_, &result, false);
  generate_struct_definition(out, f_service_, &result, false);
  generate_struct_reader(out, &result);
  generate_struct_result_writer(out, &result);

  result.set_name(tservice->get_name() + "_" + tfunction->get_name() + "_presult");
  generate_struct_declaration(f_header_, &result, false, true, true, gen_cob_style_);
  generate_struct_definition(out, f_service_, &result, false);
  generate_struct_reader(out, &result, true);
  if (gen_cob_style_) {
    generate_struct_writer(out, &result, true);
  }
}

/**
 * Generates a process function definition.
 *
 * @param tfunction The function to write a dispatcher for
 */
void t_cpp_generator::generate_process_function(t_service* tservice,
                                                t_function* tfunction,
                                                string style,
                                                bool specialized) {
  t_struct* arg_struct = tfunction->get_arglist();
  const std::vector<t_field*>& fields = arg_struct->get_members();
  vector<t_field*>::const_iterator f_iter;

  t_struct* xs = tfunction->get_xceptions();
  const std::vector<t_field*>& xceptions = xs->get_members();
  vector<t_field*>::const_iterator x_iter;
  string service_func_name = "\"" + tservice->get_name() + "." + tfunction->get_name() + "\"";

  std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);

  string prot_type = (specialized ? "Protocol_" : "::apache::thrift::protocol::TProtocol");
  string class_suffix;
  if (gen_templates_) {
    class_suffix = "T<Protocol_>";
  }

  // I tried to do this as one function.  I really did.  But it was too hard.
  if (style != "Cob") {
    // Open function
    if (gen_templates_) {
      out << indent() << "template <class Protocol_>" << endl;
    }
    const bool unnamed_oprot_seqid = tfunction->is_oneway() && !(gen_templates_ && !specialized);
    out << "void " << tservice->get_name() << "Processor" << class_suffix << "::"
        << "process_" << tfunction->get_name() << "("
        << "int32_t" << (unnamed_oprot_seqid ? ", " : " seqid, ") << prot_type << "* iprot, "
        << prot_type << "*" << (unnamed_oprot_seqid ? ", " : " oprot, ") << "void* callContext)"
        << endl;
    scope_up(out);

    string argsname = tservice->get_name() + "_" + tfunction->get_name() + "_args";
    string resultname = tservice->get_name() + "_" + tfunction->get_name() + "_result";

    if (tfunction->is_oneway() && !unnamed_oprot_seqid) {
      out << indent() << "(void) seqid;" << endl << indent() << "(void) oprot;" << endl;
    }

    out << indent() << "void* ctx = nullptr;" << endl << indent()
        << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  ctx = this->eventHandler_->getContext(" << service_func_name << ", callContext);"
        << endl << indent() << "}" << endl << indent()
        << "::apache::thrift::TProcessorContextFreer freer("
        << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
        << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  this->eventHandler_->preRead(ctx, " << service_func_name << ");" << endl << indent()
        << "}" << endl << endl << indent() << argsname << " args;" << endl << indent()
        << "args.read(iprot);" << endl << indent() << "iprot->readMessageEnd();" << endl << indent()
        << "uint32_t bytes = iprot->getTransport()->readEnd();" << endl << endl << indent()
        << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  this->eventHandler_->postRead(ctx, " << service_func_name << ", bytes);" << endl
        << indent() << "}" << endl << endl;

    // Declare result
    if (!tfunction->is_oneway()) {
      out << indent() << resultname << " result;" << endl;
    }

    // Try block for functions with exceptions
    out << indent() << "try {" << endl;
    indent_up();

    // Generate the function call
    bool first = true;
    out << indent();
    if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
      if (is_complex_type(tfunction->get_returntype())) {
        first = false;
        out << "iface_->" << tfunction->get_name() << "(result.success";
      } else {
        out << "result.success = iface_->" << tfunction->get_name() << "(";
      }
    } else {
      out << "iface_->" << tfunction->get_name() << "(";
    }
    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
      if (first) {
        first = false;
      } else {
        out << ", ";
      }
      out << "args." << (*f_iter)->get_name();
    }
    out << ");" << endl;

    // Set isset on success field
    if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
      out << indent() << "result.__isset.success = true;" << endl;
    }

    indent_down();
    out << indent() << "}";

    if (!tfunction->is_oneway()) {
      for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
        out << " catch (" << type_name((*x_iter)->get_type()) << " &" << (*x_iter)->get_name()
            << ") {" << endl;
        if (!tfunction->is_oneway()) {
          indent_up();
          out << indent() << "result." << (*x_iter)->get_name()
                          << " = std::move(" << (*x_iter)->get_name() << ");" << endl
              << indent() << "result.__isset." << (*x_iter)->get_name() << " = true;" << endl;
          indent_down();
          out << indent() << "}";
        } else {
          out << "}";
        }
      }
    }

    if (!tfunction->is_oneway()) {
      out << " catch (const std::exception& e) {" << endl;
    } else {
      out << " catch (const std::exception&) {" << endl;
    }

    indent_up();
    out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
        << indent() << "}" << endl;

    if (!tfunction->is_oneway()) {
      out << endl << indent() << "::apache::thrift::TApplicationException x(e.what());" << endl
          << indent() << "oprot->writeMessageBegin(\"" << tfunction->get_name()
          << "\", ::apache::thrift::protocol::T_EXCEPTION, seqid);" << endl << indent()
          << "x.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
          << indent() << "oprot->getTransport()->writeEnd();" << endl << indent()
          << "oprot->getTransport()->flush();" << endl;
    }
    out << indent() << "return;" << endl;
    indent_down();
    out << indent() << "}" << endl << endl;

    // Shortcut out here for oneway functions
    if (tfunction->is_oneway()) {
      out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  this->eventHandler_->asyncComplete(ctx, " << service_func_name << ");" << endl
          << indent() << "}" << endl << endl << indent() << "return;" << endl;
      indent_down();
      out << "}" << endl << endl;
      return;
    }

    // Serialize the result into a struct
    out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl << indent()
        << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\"" << tfunction->get_name()
        << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl << indent()
        << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
        << indent() << "bytes = oprot->getTransport()->writeEnd();" << endl << indent()
        << "oprot->getTransport()->flush();" << endl << endl << indent()
        << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
        << indent() << "}" << endl;

    // Close function
    scope_down(out);
    out << endl;
  }

  // Cob style.
  else {
    // Processor entry point.
    // TODO(edhall) update for callContext when TEventServer is ready
    if (gen_templates_) {
      out << indent() << "template <class Protocol_>" << endl;
    }
    out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::process_"
        << tfunction->get_name() << "(::std::function<void(bool ok)> cob, int32_t seqid, "
        << prot_type << "* iprot, " << prot_type << "* oprot)" << endl;
    scope_up(out);

    // TODO(simpkins): we could try to consoldate this
    // with the non-cob code above
    if (gen_templates_ && !specialized) {
      // If these are instances of Protocol_, instead of any old TProtocol,
      // use the specialized process function instead.
      out << indent() << "Protocol_* _iprot = dynamic_cast<Protocol_*>(iprot);" << endl << indent()
          << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl << indent()
          << "if (_iprot && _oprot) {" << endl << indent() << "  return process_"
          << tfunction->get_name() << "(cob, seqid, _iprot, _oprot);" << endl << indent() << "}"
          << endl << indent() << "T_GENERIC_PROTOCOL(this, iprot, _iprot);" << endl << indent()
          << "T_GENERIC_PROTOCOL(this, oprot, _oprot);" << endl << endl;
    }

    if (tfunction->is_oneway()) {
      out << indent() << "(void) seqid;" << endl << indent() << "(void) oprot;" << endl;
    }

    out << indent() << tservice->get_name() + "_" + tfunction->get_name() << "_args args;" << endl
        << indent() << "void* ctx = nullptr;" << endl << indent()
        << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  ctx = this->eventHandler_->getContext(" << service_func_name << ", nullptr);" << endl
        << indent() << "}" << endl << indent() << "::apache::thrift::TProcessorContextFreer freer("
        << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
        << indent() << "try {" << endl;
    indent_up();
    out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  this->eventHandler_->preRead(ctx, " << service_func_name << ");" << endl << indent()
        << "}" << endl << indent() << "args.read(iprot);" << endl << indent()
        << "iprot->readMessageEnd();" << endl << indent()
        << "uint32_t bytes = iprot->getTransport()->readEnd();" << endl << indent()
        << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "  this->eventHandler_->postRead(ctx, " << service_func_name << ", bytes);" << endl
        << indent() << "}" << endl;
    scope_down(out);

    // TODO(dreiss): Handle TExceptions?  Expose to server?
    out << indent() << "catch (const std::exception&) {" << endl << indent()
        << "  if (this->eventHandler_.get() != nullptr) {" << endl << indent()
        << "    this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
        << indent() << "  }" << endl << indent() << "  return cob(false);" << endl << indent()
        << "}" << endl;

    if (tfunction->is_oneway()) {
      out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  this->eventHandler_->asyncComplete(ctx, " << service_func_name << ");" << endl
          << indent() << "}" << endl;
    }
    // TODO(dreiss): Figure out a strategy for exceptions in async handlers.
    out << indent() << "freer.unregister();" << endl;
    if (tfunction->is_oneway()) {
      // No return.  Just hand off our cob.
      // TODO(dreiss): Call the cob immediately?
      out << indent() << "iface_->" << tfunction->get_name() << "("
          << "::std::bind(cob, true)" << endl;
      indent_up();
      indent_up();
    } else {
      string ret_arg, ret_placeholder;
      if (!tfunction->get_returntype()->is_void()) {
        ret_arg = ", const " + type_name(tfunction->get_returntype()) + "& _return";
        ret_placeholder = ", ::std::placeholders::_1";
      }

      // When gen_templates_ is true, the return_ and throw_ functions are
      // overloaded.  We have to declare pointers to them so that the compiler
      // can resolve the correct overloaded version.
      out << indent() << "void (" << tservice->get_name() << "AsyncProcessor" << class_suffix
          << "::*return_fn)(::std::function<void(bool ok)> "
          << "cob, int32_t seqid, " << prot_type << "* oprot, void* ctx" << ret_arg
          << ") =" << endl;
      out << indent() << "  &" << tservice->get_name() << "AsyncProcessor" << class_suffix
          << "::return_" << tfunction->get_name() << ";" << endl;
      if (!xceptions.empty()) {
        out << indent() << "void (" << tservice->get_name() << "AsyncProcessor" << class_suffix
            << "::*throw_fn)(::std::function<void(bool ok)> "
            << "cob, int32_t seqid, " << prot_type << "* oprot, void* ctx, "
            << "::apache::thrift::TDelayedException* _throw) =" << endl;
        out << indent() << "  &" << tservice->get_name() << "AsyncProcessor" << class_suffix
            << "::throw_" << tfunction->get_name() << ";" << endl;
      }

      out << indent() << "iface_->" << tfunction->get_name() << "(" << endl;
      indent_up();
      indent_up();
      out << indent() << "::std::bind(return_fn, this, cob, seqid, oprot, ctx" << ret_placeholder
          << ")";
      if (!xceptions.empty()) {
        out << ',' << endl << indent() << "::std::bind(throw_fn, this, cob, seqid, oprot, "
            << "ctx, ::std::placeholders::_1)";
      }
    }

    // XXX Whitespace cleanup.
    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
      out << ',' << endl << indent() << "args." << (*f_iter)->get_name();
    }
    out << ");" << endl;
    indent_down();
    indent_down();
    scope_down(out);
    out << endl;

    // Normal return.
    if (!tfunction->is_oneway()) {
      string ret_arg_decl, ret_arg_name;
      if (!tfunction->get_returntype()->is_void()) {
        ret_arg_decl = ", const " + type_name(tfunction->get_returntype()) + "& _return";
        ret_arg_name = ", _return";
      }
      if (gen_templates_) {
        out << indent() << "template <class Protocol_>" << endl;
      }
      out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::return_"
          << tfunction->get_name() << "(::std::function<void(bool ok)> cob, int32_t seqid, "
          << prot_type << "* oprot, void* ctx" << ret_arg_decl << ')' << endl;
      scope_up(out);

      if (gen_templates_ && !specialized) {
        // If oprot is a Protocol_ instance,
        // use the specialized return function instead.
        out << indent() << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl
            << indent() << "if (_oprot) {" << endl << indent() << "  return return_"
            << tfunction->get_name() << "(cob, seqid, _oprot, ctx" << ret_arg_name << ");" << endl
            << indent() << "}" << endl << indent() << "T_GENERIC_PROTOCOL(this, oprot, _oprot);"
            << endl << endl;
      }

      out << indent() << tservice->get_name() << "_" << tfunction->get_name() << "_presult result;"
          << endl;
      if (!tfunction->get_returntype()->is_void()) {
        // The const_cast here is unfortunate, but it would be a pain to avoid,
        // and we only do a write with this struct, which is const-safe.
        out << indent() << "result.success = const_cast<" << type_name(tfunction->get_returntype())
            << "*>(&_return);" << endl << indent() << "result.__isset.success = true;" << endl;
      }
      // Serialize the result into a struct
      out << endl << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  ctx = this->eventHandler_->getContext(" << service_func_name << ", nullptr);" << endl
          << indent() << "}" << endl << indent()
          << "::apache::thrift::TProcessorContextFreer freer("
          << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
          << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl
          << indent() << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\""
          << tfunction->get_name() << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl
          << indent() << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();"
          << endl << indent() << "uint32_t bytes = oprot->getTransport()->writeEnd();" << endl
          << indent() << "oprot->getTransport()->flush();" << endl << indent()
          << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
          << indent() << "}" << endl << indent() << "return cob(true);" << endl;
      scope_down(out);
      out << endl;
    }

    // Exception return.
    if (!tfunction->is_oneway() && !xceptions.empty()) {
      if (gen_templates_) {
        out << indent() << "template <class Protocol_>" << endl;
      }
      out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::throw_"
          << tfunction->get_name() << "(::std::function<void(bool ok)> cob, int32_t seqid, "
          << prot_type << "* oprot, void* ctx, "
          << "::apache::thrift::TDelayedException* _throw)" << endl;
      scope_up(out);

      if (gen_templates_ && !specialized) {
        // If oprot is a Protocol_ instance,
        // use the specialized throw function instead.
        out << indent() << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl
            << indent() << "if (_oprot) {" << endl << indent() << "  return throw_"
            << tfunction->get_name() << "(cob, seqid, _oprot, ctx, _throw);" << endl << indent()
            << "}" << endl << indent() << "T_GENERIC_PROTOCOL(this, oprot, _oprot);" << endl
            << endl;
      }

      // Get the event handler context
      out << endl << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  ctx = this->eventHandler_->getContext(" << service_func_name << ", nullptr);" << endl
          << indent() << "}" << endl << indent()
          << "::apache::thrift::TProcessorContextFreer freer("
          << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl;

      // Throw the TDelayedException, and catch the result
      out << indent() << tservice->get_name() << "_" << tfunction->get_name() << "_result result;"
          << endl << endl << indent() << "try {" << endl;
      indent_up();
      out << indent() << "_throw->throw_it();" << endl << indent() << "return cob(false);"
          << endl; // Is this possible?  TBD.
      indent_down();
      out << indent() << '}';
      for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
        out << "  catch (" << type_name((*x_iter)->get_type()) << " &" << (*x_iter)->get_name()
            << ") {" << endl;
        indent_up();
        out << indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name()
            << ";" << endl << indent() << "result.__isset." << (*x_iter)->get_name() << " = true;"
            << endl;
        scope_down(out);
      }

      // Handle the case where an undeclared exception is thrown
      out << " catch (std::exception& e) {" << endl;
      indent_up();
      out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
          << indent() << "}" << endl << endl << indent()
          << "::apache::thrift::TApplicationException x(e.what());" << endl << indent()
          << "oprot->writeMessageBegin(\"" << tfunction->get_name()
          << "\", ::apache::thrift::protocol::T_EXCEPTION, seqid);" << endl << indent()
          << "x.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
          << indent() << "oprot->getTransport()->writeEnd();" << endl << indent()
          << "oprot->getTransport()->flush();" << endl <<
          // We pass true to the cob here, since we did successfully write a
          // response, even though it is an exception response.
          // It looks like the argument is currently ignored, anyway.
          indent() << "return cob(true);" << endl;
      scope_down(out);

      // Serialize the result into a struct
      out << indent() << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl
          << indent() << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\""
          << tfunction->get_name() << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl
          << indent() << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();"
          << endl << indent() << "uint32_t bytes = oprot->getTransport()->writeEnd();" << endl
          << indent() << "oprot->getTransport()->flush();" << endl << indent()
          << "if (this->eventHandler_.get() != nullptr) {" << endl << indent()
          << "  this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
          << indent() << "}" << endl << indent() << "return cob(true);" << endl;
      scope_down(out);
      out << endl;
    } // for each function
  }   // cob style
}

/**
 * Generates a skeleton file of a server
 *
 * @param tservice The service to generate a server for.
 */
void t_cpp_generator::generate_service_skeleton(t_service* tservice) {
  string svcname = tservice->get_name();

  // Service implementation file includes
  string f_skeleton_name = get_out_dir() + svcname + "_server.skeleton.cpp";

  string ns = namespace_prefix(tservice->get_program()->get_namespace("cpp"));

  ofstream_with_content_based_conditional_update f_skeleton;
  f_skeleton.open(f_skeleton_name.c_str());
  f_skeleton << "// This autogenerated skeleton file illustrates how to build a server." << endl
             << "// You should copy it to another filename to avoid overwriting it." << endl << endl
             << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl
             << "#include <thrift/protocol/TBinaryProtocol.h>" << endl
             << "#include <thrift/server/TSimpleServer.h>" << endl
             << "#include <thrift/transport/TServerSocket.h>" << endl
             << "#include <thrift/transport/TBufferTransports.h>" << endl << endl
             << "using namespace ::apache::thrift;" << endl
             << "using namespace ::apache::thrift::protocol;" << endl
             << "using namespace ::apache::thrift::transport;" << endl
             << "using namespace ::apache::thrift::server;" << endl << endl;

  // the following code would not compile:
  // using namespace ;
  // using namespace ::;
  if ((!ns.empty()) && (ns.compare(" ::") != 0)) {
    f_skeleton << "using namespace " << string(ns, 0, ns.size() - 2) << ";" << endl << endl;
  }

  f_skeleton << "class " << svcname << "Handler : virtual public " << svcname << "If {" << endl
             << " public:" << endl;
  indent_up();
  f_skeleton << indent() << svcname << "Handler() {" << endl << indent()
             << "  // Your initialization goes here" << endl << indent() << "}" << endl << endl;

  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    generate_java_doc(f_skeleton, *f_iter);
    f_skeleton << indent() << function_signature(*f_iter, "") << " {" << endl << indent()
               << "  // Your implementation goes here" << endl << indent() << "  printf(\""
               << (*f_iter)->get_name() << "\\n\");" << endl << indent() << "}" << endl << endl;
  }

  indent_down();
  f_skeleton << "};" << endl << endl;

  f_skeleton << indent() << "int main(int argc, char **argv) {" << endl;
  indent_up();
  f_skeleton
      << indent() << "int port = 9090;" << endl << indent() << "::std::shared_ptr<" << svcname
      << "Handler> handler(new " << svcname << "Handler());" << endl << indent()
      << "::std::shared_ptr<TProcessor> processor(new " << svcname << "Processor(handler));" << endl
      << indent() << "::std::shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));"
      << endl << indent()
      << "::std::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());" << endl
      << indent() << "::std::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());"
      << endl << endl << indent()
      << "TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);"
      << endl << indent() << "server.serve();" << endl << indent() << "return 0;" << endl;
  indent_down();
  f_skeleton << "}" << endl << endl;

  // Close the files
  f_skeleton.close();
}

/**
 * Deserializes a field of any type.
 */
void t_cpp_generator::generate_deserialize_field(ostream& out,
                                                 t_field* tfield,
                                                 string prefix,
                                                 string suffix) {
  t_type* type = get_true_type(tfield->get_type());

  if (type->is_void()) {
    throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " + prefix + tfield->get_name();
  }

  string name = prefix + tfield->get_name() + suffix;

  if (type->is_struct() || type->is_xception()) {
    generate_deserialize_struct(out, (t_struct*)type, name, is_reference(tfield));
  } else if (type->is_container()) {
    generate_deserialize_container(out, type, name);
  } else if (type->is_base_type()) {
    indent(out) << "xfer += iprot->";
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_VOID:
      throw "compiler error: cannot serialize void field in a struct: " + name;
      break;
    case t_base_type::TYPE_STRING:
      if (type->is_binary()) {
        out << "readBinary(" << name << ");";
      } else {
        out << "readString(" << name << ");";
      }
      break;
    case t_base_type::TYPE_BOOL:
      out << "readBool(" << name << ");";
      break;
    case t_base_type::TYPE_I8:
      out << "readByte(" << name << ");";
      break;
    case t_base_type::TYPE_I16:
      out << "readI16(" << name << ");";
      break;
    case t_base_type::TYPE_I32:
      out << "readI32(" << name << ");";
      break;
    case t_base_type::TYPE_I64:
      out << "readI64(" << name << ");";
      break;
    case t_base_type::TYPE_DOUBLE:
      out << "readDouble(" << name << ");";
      break;
    default:
      throw "compiler error: no C++ reader for base type " + t_base_type::t_base_name(tbase) + name;
    }
    out << endl;
  } else if (type->is_enum()) {
    string t = tmp("ecast");
    out << indent() << "int32_t " << t << ";" << endl << indent() << "xfer += iprot->readI32(" << t
        << ");" << endl << indent() << name << " = static_cast<" 
        << type_name(type) << ">(" << t << ");" << endl;
  } else {
    printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
           tfield->get_name().c_str(),
           type_name(type).c_str());
  }
}

/**
 * Generates an unserializer for a variable. This makes two key assumptions,
 * first that there is a const char* variable named data that points to the
 * buffer for deserialization, and that there is a variable protocol which
 * is a reference to a TProtocol serialization object.
 */
void t_cpp_generator::generate_deserialize_struct(ostream& out,
                                                  t_struct* tstruct,
                                                  string prefix,
                                                  bool pointer) {
  if (pointer) {
    indent(out) << "if (!" << prefix << ") { " << endl;
    indent(out) << "  " << prefix << " = ::std::shared_ptr<" << type_name(tstruct) << ">(new "
                << type_name(tstruct) << ");" << endl;
    indent(out) << "}" << endl;
    indent(out) << "xfer += " << prefix << "->read(iprot);" << endl;
    indent(out) << "bool wasSet = false;" << endl;
    const vector<t_field*>& members = tstruct->get_members();
    vector<t_field*>::const_iterator f_iter;
    for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {

      indent(out) << "if (" << prefix << "->__isset." << (*f_iter)->get_name()
                  << ") { wasSet = true; }" << endl;
    }
    indent(out) << "if (!wasSet) { " << prefix << ".reset(); }" << endl;
  } else {
    indent(out) << "xfer += " << prefix << ".read(iprot);" << endl;
  }
}

void t_cpp_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) {
  scope_up(out);

  string size = tmp("_size");
  string ktype = tmp("_ktype");
  string vtype = tmp("_vtype");
  string etype = tmp("_etype");

  t_container* tcontainer = (t_container*)ttype;
  bool use_push = tcontainer->has_cpp_name();

  indent(out) << prefix << ".clear();" << endl << indent() << "uint32_t " << size << ";" << endl;

  // Declare variables, read header
  if (ttype->is_map()) {
    out << indent() << "::apache::thrift::protocol::TType " << ktype << ";" << endl << indent()
        << "::apache::thrift::protocol::TType " << vtype << ";" << endl << indent()
        << "xfer += iprot->readMapBegin(" << ktype << ", " << vtype << ", " << size << ");" << endl;
  } else if (ttype->is_set()) {
    out << indent() << "::apache::thrift::protocol::TType " << etype << ";" << endl << indent()
        << "xfer += iprot->readSetBegin(" << etype << ", " << size << ");" << endl;
  } else if (ttype->is_list()) {
    out << indent() << "::apache::thrift::protocol::TType " << etype << ";" << endl << indent()
        << "xfer += iprot->readListBegin(" << etype << ", " << size << ");" << endl;
    if (!use_push) {
      indent(out) << prefix << ".resize(" << size << ");" << endl;
    }
  }

  // For loop iterates over elements
  string i = tmp("_i");
  out << indent() << "uint32_t " << i << ";" << endl << indent() << "for (" << i << " = 0; " << i
      << " < " << size << "; ++" << i << ")" << endl;

  scope_up(out);

  if (ttype->is_map()) {
    generate_deserialize_map_element(out, (t_map*)ttype, prefix);
  } else if (ttype->is_set()) {
    generate_deserialize_set_element(out, (t_set*)ttype, prefix);
  } else if (ttype->is_list()) {
    generate_deserialize_list_element(out, (t_list*)ttype, prefix, use_push, i);
  }

  scope_down(out);

  // Read container end
  if (ttype->is_map()) {
    indent(out) << "xfer += iprot->readMapEnd();" << endl;
  } else if (ttype->is_set()) {
    indent(out) << "xfer += iprot->readSetEnd();" << endl;
  } else if (ttype->is_list()) {
    indent(out) << "xfer += iprot->readListEnd();" << endl;
  }

  scope_down(out);
}

/**
 * Generates code to deserialize a map
 */
void t_cpp_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) {
  string key = tmp("_key");
  string val = tmp("_val");
  t_field fkey(tmap->get_key_type(), key);
  t_field fval(tmap->get_val_type(), val);

  out << indent() << declare_field(&fkey) << endl;

  generate_deserialize_field(out, &fkey);
  indent(out) << declare_field(&fval, false, false, false, true) << " = " << prefix << "[" << key
              << "];" << endl;

  generate_deserialize_field(out, &fval);
}

void t_cpp_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) {
  string elem = tmp("_elem");
  t_field felem(tset->get_elem_type(), elem);

  indent(out) << declare_field(&felem) << endl;

  generate_deserialize_field(out, &felem);

  indent(out) << prefix << ".insert(" << elem << ");" << endl;
}

void t_cpp_generator::generate_deserialize_list_element(ostream& out,
                                                        t_list* tlist,
                                                        string prefix,
                                                        bool use_push,
                                                        string index) {
  if (use_push) {
    string elem = tmp("_elem");
    t_field felem(tlist->get_elem_type(), elem);
    indent(out) << declare_field(&felem) << endl;
    generate_deserialize_field(out, &felem);
    indent(out) << prefix << ".push_back(" << elem << ");" << endl;
  } else {
    t_field felem(tlist->get_elem_type(), prefix + "[" + index + "]");
    generate_deserialize_field(out, &felem);
  }
}

/**
 * Serializes a field of any type.
 *
 * @param tfield The field to serialize
 * @param prefix Name to prepend to field name
 */
void t_cpp_generator::generate_serialize_field(ostream& out,
                                               t_field* tfield,
                                               string prefix,
                                               string suffix) {
  t_type* type = get_true_type(tfield->get_type());

  string name = prefix + tfield->get_name() + suffix;

  // Do nothing for void types
  if (type->is_void()) {
    throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " + name;
  }

  if (type->is_struct() || type->is_xception()) {
    generate_serialize_struct(out, (t_struct*)type, name, is_reference(tfield));
  } else if (type->is_container()) {
    generate_serialize_container(out, type, name);
  } else if (type->is_base_type() || type->is_enum()) {

    indent(out) << "xfer += oprot->";

    if (type->is_base_type()) {
      t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
      switch (tbase) {
      case t_base_type::TYPE_VOID:
        throw "compiler error: cannot serialize void field in a struct: " + name;
        break;
      case t_base_type::TYPE_STRING:
        if (type->is_binary()) {
          out << "writeBinary(" << name << ");";
        } else {
          out << "writeString(" << name << ");";
        }
        break;
      case t_base_type::TYPE_BOOL:
        out << "writeBool(" << name << ");";
        break;
      case t_base_type::TYPE_I8:
        out << "writeByte(" << name << ");";
        break;
      case t_base_type::TYPE_I16:
        out << "writeI16(" << name << ");";
        break;
      case t_base_type::TYPE_I32:
        out << "writeI32(" << name << ");";
        break;
      case t_base_type::TYPE_I64:
        out << "writeI64(" << name << ");";
        break;
      case t_base_type::TYPE_DOUBLE:
        out << "writeDouble(" << name << ");";
        break;
      default:
        throw "compiler error: no C++ writer for base type " + t_base_type::t_base_name(tbase)
            + name;
      }
    } else if (type->is_enum()) {
      out << "writeI32(static_cast<int32_t>(" << name << "));";
    }
    out << endl;
  } else {
    printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s' TYPE '%s'\n",
           name.c_str(),
           type_name(type).c_str());
  }
}

/**
 * Serializes all the members of a struct.
 *
 * @param tstruct The struct to serialize
 * @param prefix  String prefix to attach to all fields
 */
void t_cpp_generator::generate_serialize_struct(ostream& out,
                                                t_struct* tstruct,
                                                string prefix,
                                                bool pointer) {
  if (pointer) {
    indent(out) << "if (" << prefix << ") {" << endl;
    indent(out) << "  xfer += " << prefix << "->write(oprot); " << endl;
    indent(out) << "} else {"
                << "oprot->writeStructBegin(\"" << tstruct->get_name() << "\"); " << endl;
    indent(out) << "  oprot->writeStructEnd();" << endl;
    indent(out) << "  oprot->writeFieldStop();" << endl;
    indent(out) << "}" << endl;
  } else {
    indent(out) << "xfer += " << prefix << ".write(oprot);" << endl;
  }
}

void t_cpp_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) {
  scope_up(out);

  if (ttype->is_map()) {
    indent(out) << "xfer += oprot->writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type())
                << ", " << type_to_enum(((t_map*)ttype)->get_val_type()) << ", "
                << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
  } else if (ttype->is_set()) {
    indent(out) << "xfer += oprot->writeSetBegin(" << type_to_enum(((t_set*)ttype)->get_elem_type())
                << ", "
                << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
  } else if (ttype->is_list()) {
    indent(out) << "xfer += oprot->writeListBegin("
                << type_to_enum(((t_list*)ttype)->get_elem_type()) << ", "
                << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
  }

  string iter = tmp("_iter");
  out << indent() << type_name(ttype) << "::const_iterator " << iter << ";" << endl << indent()
      << "for (" << iter << " = " << prefix << ".begin(); " << iter << " != " << prefix
      << ".end(); ++" << iter << ")" << endl;
  scope_up(out);
  if (ttype->is_map()) {
    generate_serialize_map_element(out, (t_map*)ttype, iter);
  } else if (ttype->is_set()) {
    generate_serialize_set_element(out, (t_set*)ttype, iter);
  } else if (ttype->is_list()) {
    generate_serialize_list_element(out, (t_list*)ttype, iter);
  }
  scope_down(out);

  if (ttype->is_map()) {
    indent(out) << "xfer += oprot->writeMapEnd();" << endl;
  } else if (ttype->is_set()) {
    indent(out) << "xfer += oprot->writeSetEnd();" << endl;
  } else if (ttype->is_list()) {
    indent(out) << "xfer += oprot->writeListEnd();" << endl;
  }

  scope_down(out);
}

/**
 * Serializes the members of a map.
 *
 */
void t_cpp_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter) {
  t_field kfield(tmap->get_key_type(), iter + "->first");
  generate_serialize_field(out, &kfield, "");

  t_field vfield(tmap->get_val_type(), iter + "->second");
  generate_serialize_field(out, &vfield, "");
}

/**
 * Serializes the members of a set.
 */
void t_cpp_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) {
  t_field efield(tset->get_elem_type(), "(*" + iter + ")");
  generate_serialize_field(out, &efield, "");
}

/**
 * Serializes the members of a list.
 */
void t_cpp_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) {
  t_field efield(tlist->get_elem_type(), "(*" + iter + ")");
  generate_serialize_field(out, &efield, "");
}

/**
 * Makes a :: prefix for a namespace
 *
 * @param ns The namespace, w/ periods in it
 * @return Namespaces
 */
string t_cpp_generator::namespace_prefix(string ns) {
  // Always start with "::", to avoid possible name collisions with
  // other names in one of the current namespaces.
  //
  // We also need a leading space, in case the name is used inside of a
  // template parameter.  "MyTemplate<::foo::Bar>" is not valid C++,
  // since "<:" is an alternative token for "[".
  string result = " ::";

  if (ns.size() == 0) {
    return result;
  }
  string::size_type loc;
  while ((loc = ns.find(".")) != string::npos) {
    result += ns.substr(0, loc);
    result += "::";
    ns = ns.substr(loc + 1);
  }
  if (ns.size() > 0) {
    result += ns + "::";
  }
  return result;
}

/**
 * Opens namespace.
 *
 * @param ns The namespace, w/ periods in it
 * @return Namespaces
 */
string t_cpp_generator::namespace_open(string ns) {
  if (ns.size() == 0) {
    return "";
  }
  string result = "";
  string separator = "";
  string::size_type loc;
  while ((loc = ns.find(".")) != string::npos) {
    result += separator;
    result += "namespace ";
    result += ns.substr(0, loc);
    result += " {";
    separator = " ";
    ns = ns.substr(loc + 1);
  }
  if (ns.size() > 0) {
    result += separator + "namespace " + ns + " {";
  }
  return result;
}

/**
 * Closes namespace.
 *
 * @param ns The namespace, w/ periods in it
 * @return Namespaces
 */
string t_cpp_generator::namespace_close(string ns) {
  if (ns.size() == 0) {
    return "";
  }
  string result = "}";
  string::size_type loc;
  while ((loc = ns.find(".")) != string::npos) {
    result += "}";
    ns = ns.substr(loc + 1);
  }
  result += " // namespace";
  return result;
}

/**
 * Returns a C++ type name
 *
 * @param ttype The type
 * @return String of the type name, i.e. std::set<type>
 */
string t_cpp_generator::type_name(t_type* ttype, bool in_typedef, bool arg) {
  if (ttype->is_base_type()) {
    string bname = base_type_name(((t_base_type*)ttype)->get_base());
    std::map<string, string>::iterator it = ttype->annotations_.find("cpp.type");
    if (it != ttype->annotations_.end()) {
      bname = it->second;
    }

    if (!arg) {
      return bname;
    }

    if (((t_base_type*)ttype)->get_base() == t_base_type::TYPE_STRING) {
      return "const " + bname + "&";
    } else {
      return "const " + bname;
    }
  }

  // Check for a custom overloaded C++ name
  if (ttype->is_container()) {
    string cname;

    t_container* tcontainer = (t_container*)ttype;
    if (tcontainer->has_cpp_name()) {
      cname = tcontainer->get_cpp_name();
    } else if (ttype->is_map()) {
      t_map* tmap = (t_map*)ttype;
      cname = "std::map<" + type_name(tmap->get_key_type(), in_typedef) + ", "
              + type_name(tmap->get_val_type(), in_typedef) + "> ";
    } else if (ttype->is_set()) {
      t_set* tset = (t_set*)ttype;
      cname = "std::set<" + type_name(tset->get_elem_type(), in_typedef) + "> ";
    } else if (ttype->is_list()) {
      t_list* tlist = (t_list*)ttype;
      cname = "std::vector<" + type_name(tlist->get_elem_type(), in_typedef) + "> ";
    }

    if (arg) {
      return "const " + cname + "&";
    } else {
      return cname;
    }
  }

  string class_prefix;
  if (in_typedef && (ttype->is_struct() || ttype->is_xception())) {
    class_prefix = "class ";
  }

  // Check if it needs to be namespaced
  string pname;
  t_program* program = ttype->get_program();
  if (program != nullptr && program != program_) {
    pname = class_prefix + namespace_prefix(program->get_namespace("cpp")) + ttype->get_name();
  } else {
    pname = class_prefix + ttype->get_name();
  }

  if (ttype->is_enum() && !gen_pure_enums_) {
    pname += "::type";
  }

  if (arg) {
    if (is_complex_type(ttype)) {
      return "const " + pname + "&";
    } else {
      return "const " + pname;
    }
  } else {
    return pname;
  }
}

/**
 * Returns the C++ type that corresponds to the thrift type.
 *
 * @param tbase The base type
 * @return Explicit C++ type, i.e. "int32_t"
 */
string t_cpp_generator::base_type_name(t_base_type::t_base tbase) {
  switch (tbase) {
  case t_base_type::TYPE_VOID:
    return "void";
  case t_base_type::TYPE_STRING:
    return "std::string";
  case t_base_type::TYPE_BOOL:
    return "bool";
  case t_base_type::TYPE_I8:
    return "int8_t";
  case t_base_type::TYPE_I16:
    return "int16_t";
  case t_base_type::TYPE_I32:
    return "int32_t";
  case t_base_type::TYPE_I64:
    return "int64_t";
  case t_base_type::TYPE_DOUBLE:
    return "double";
  default:
    throw "compiler error: no C++ base type name for base type " + t_base_type::t_base_name(tbase);
  }
}

/**
 * Declares a field, which may include initialization as necessary.
 *
 * @param ttype The type
 * @return Field declaration, i.e. int x = 0;
 */
string t_cpp_generator::declare_field(t_field* tfield,
                                      bool init,
                                      bool pointer,
                                      bool constant,
                                      bool reference) {
  // TODO(mcslee): do we ever need to initialize the field?
  string result = "";
  if (constant) {
    result += "const ";
  }
  result += type_name(tfield->get_type());
  if (is_reference(tfield)) {
    result = "::std::shared_ptr<" + result + ">";
  }
  if (pointer) {
    result += "*";
  }
  if (reference) {
    result += "&";
  }
  result += " " + tfield->get_name();
  if (init) {
    t_type* type = get_true_type(tfield->get_type());

    if (type->is_base_type()) {
      t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
      switch (tbase) {
      case t_base_type::TYPE_VOID:
      case t_base_type::TYPE_STRING:
        break;
      case t_base_type::TYPE_BOOL:
        result += " = false";
        break;
      case t_base_type::TYPE_I8:
      case t_base_type::TYPE_I16:
      case t_base_type::TYPE_I32:
      case t_base_type::TYPE_I64:
        result += " = 0";
        break;
      case t_base_type::TYPE_DOUBLE:
        result += " = 0.0";
        break;
      default:
        throw "compiler error: no C++ initializer for base type " + t_base_type::t_base_name(tbase);
      }
    } else if (type->is_enum()) {
      result += " = static_cast<" + type_name(type) + ">(0)";
    }
  }
  if (!reference) {
    result += ";";
  }
  return result;
}

/**
 * Renders a function signature of the form 'type name(args)'
 *
 * @param tfunction Function definition
 * @return String of rendered function definition
 */
string t_cpp_generator::function_signature(t_function* tfunction,
                                           string style,
                                           string prefix,
                                           bool name_params) {
  t_type* ttype = tfunction->get_returntype();
  t_struct* arglist = tfunction->get_arglist();
  bool has_xceptions = !tfunction->get_xceptions()->get_members().empty();

  if (style == "") {
    if (is_complex_type(ttype)) {
      return "void " + prefix + tfunction->get_name() + "(" + type_name(ttype)
             + (name_params ? "& _return" : "& /* _return */")
             + argument_list(arglist, name_params, true) + ")";
    } else {
      return type_name(ttype) + " " + prefix + tfunction->get_name() + "("
             + argument_list(arglist, name_params) + ")";
    }
  } else if (style.substr(0, 3) == "Cob") {
    string cob_type;
    string exn_cob;
    if (style == "CobCl") {
      cob_type = "(" + service_name_ + "CobClient";
      if (gen_templates_) {
        cob_type += "T<Protocol_>";
      }
      cob_type += "* client)";
    } else if (style == "CobSv") {
      cob_type = (ttype->is_void() ? "()" : ("(" + type_name(ttype) + " const& _return)"));
      if (has_xceptions) {
        exn_cob
            = ", ::std::function<void(::apache::thrift::TDelayedException* _throw)> /* exn_cob */";
      }
    } else {
      throw "UNKNOWN STYLE";
    }

    return "void " + prefix + tfunction->get_name() + "(::std::function<void" + cob_type + "> cob"
           + exn_cob + argument_list(arglist, name_params, true) + ")";
  } else {
    throw "UNKNOWN STYLE";
  }
}

/**
 * Renders a field list
 *
 * @param tstruct The struct definition
 * @return Comma sepearated list of all field names in that struct
 */
string t_cpp_generator::argument_list(t_struct* tstruct, bool name_params, bool start_comma) {
  string result = "";

  const vector<t_field*>& fields = tstruct->get_members();
  vector<t_field*>::const_iterator f_iter;
  bool first = !start_comma;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    if (first) {
      first = false;
    } else {
      result += ", ";
    }
    result += type_name((*f_iter)->get_type(), false, true) + " "
              + (name_params ? (*f_iter)->get_name() : "/* " + (*f_iter)->get_name() + " */");
  }
  return result;
}

/**
 * Converts the parse type to a C++ enum string for the given type.
 *
 * @param type Thrift Type
 * @return String of C++ code to definition of that type constant
 */
string t_cpp_generator::type_to_enum(t_type* type) {
  type = get_true_type(type);

  if (type->is_base_type()) {
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_VOID:
      throw "NO T_VOID CONSTRUCT";
    case t_base_type::TYPE_STRING:
      return "::apache::thrift::protocol::T_STRING";
    case t_base_type::TYPE_BOOL:
      return "::apache::thrift::protocol::T_BOOL";
    case t_base_type::TYPE_I8:
      return "::apache::thrift::protocol::T_BYTE";
    case t_base_type::TYPE_I16:
      return "::apache::thrift::protocol::T_I16";
    case t_base_type::TYPE_I32:
      return "::apache::thrift::protocol::T_I32";
    case t_base_type::TYPE_I64:
      return "::apache::thrift::protocol::T_I64";
    case t_base_type::TYPE_DOUBLE:
      return "::apache::thrift::protocol::T_DOUBLE";
    }
  } else if (type->is_enum()) {
    return "::apache::thrift::protocol::T_I32";
  } else if (type->is_struct()) {
    return "::apache::thrift::protocol::T_STRUCT";
  } else if (type->is_xception()) {
    return "::apache::thrift::protocol::T_STRUCT";
  } else if (type->is_map()) {
    return "::apache::thrift::protocol::T_MAP";
  } else if (type->is_set()) {
    return "::apache::thrift::protocol::T_SET";
  } else if (type->is_list()) {
    return "::apache::thrift::protocol::T_LIST";
  }

  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
}


bool t_cpp_generator::is_struct_storage_not_throwing(t_struct* tstruct) const {
  vector<t_field*> members = tstruct->get_members();

  for(size_t i=0; i < members.size(); ++i)  {
    t_type* type = get_true_type(members[i]->get_type());

    if(type->is_enum())
      continue;
    if(type->is_xception())
      return false;
    if(type->is_base_type()) switch(((t_base_type*)type)->get_base()) {
      case t_base_type::TYPE_BOOL:
      case t_base_type::TYPE_I8:
      case t_base_type::TYPE_I16:
      case t_base_type::TYPE_I32:
      case t_base_type::TYPE_I64:
      case t_base_type::TYPE_DOUBLE:
        continue;
      case t_base_type::TYPE_VOID:
      case t_base_type::TYPE_STRING:
      default:
        return false;
    }
    if(type->is_struct()) {
      const vector<t_field*>& more = ((t_struct*)type)->get_members();
      for(auto it = more.begin(); it < more.end(); ++it) {
        if(std::find(members.begin(), members.end(), *it) == members.end())
          members.push_back(*it);
      }
      continue;
    }
    return false; // rest-as-throwing(require-alloc)
  }
  return true;
}


string t_cpp_generator::get_include_prefix(const t_program& program) const {
  string include_prefix = program.get_include_prefix();
  if (!use_include_prefix_ || (include_prefix.size() > 0 && include_prefix[0] == '/')) {
    // if flag is turned off or this is absolute path, return empty prefix
    return "";
  }

  string::size_type last_slash = string::npos;
  if ((last_slash = include_prefix.rfind("/")) != string::npos) {
    return include_prefix.substr(0, last_slash)
           + (get_program()->is_out_path_absolute() ? "/" : "/" + out_dir_base_ + "/");
  }

  return "";
}

string t_cpp_generator::get_legal_program_name(std::string program_name)
{
  std::size_t found = 0;

  while(true) {
    found = program_name.find('.');

    if(found != string::npos) {
      program_name = program_name.replace(found, 1, "_");
    } else {
      break;
    }
  }

  return program_name;
}

THRIFT_REGISTER_GENERATOR(
    cpp,
    "C++",
    "    cob_style:       Generate \"Continuation OBject\"-style classes.\n"
    "    no_client_completion:\n"
    "                     Omit calls to completion__() in CobClient class.\n"
    "    no_default_operators:\n"
    "                     Omits generation of default operators ==, != and <\n"
    "    templates:       Generate templatized reader/writer methods.\n"
    "    pure_enums:      Generate pure enums instead of wrapper classes.\n"
    "    include_prefix:  Use full include paths in generated files.\n"
    "    moveable_types:  Generate move constructors and assignment operators.\n"
    "    no_ostream_operators:\n"
    "                     Omit generation of ostream definitions.\n"
    "    no_skeleton:     Omits generation of skeleton.\n")