Debian Codegraph @

pypy/module/_cppyy/test/test_templates.py

raw symbols SCIP
1 import py, os
2 from .support import setup_make, soext
3
4 currpath = py.path.local(__file__).dirpath()
5 test_dct = str(currpath.join("templatesDict"))+soext
6
7 def setup_module(mod):
8 setup_make("templates")
9
10
11 class AppTestTEMPLATES:
12 spaceconfig = dict(usemodules=['_cppyy', '_rawffi', 'itertools'])
13
14 def setup_class(cls):
15 cls.w_test_dct = cls.space.newtext(test_dct)
16 cls.w_templates = cls.space.appexec([], """():
17 import ctypes, _cppyy
18 _cppyy._post_import_startup()
19 return ctypes.CDLL(%r, ctypes.RTLD_GLOBAL)""" % (test_dct, ))
20
21 def test01_template_member_functions(self):
22 """Template member functions lookup and calls"""
23
24 import _cppyy as cppyy
25 import sys
26
27 m = cppyy.gbl.MyTemplatedMethodClass()
28
29 # implicit (called before other tests to check caching)
30 assert m.get_size(1) == m.get_int_size()+1
31
32 # pre-instantiated
33 assert m.get_size['char']() == m.get_char_size()
34 assert m.get_size[int]() == m.get_int_size()
35
36 # specialized
37 if sys.hexversion >= 0x3000000:
38 targ = 'long'
39 else:
40 targ = long
41 assert m.get_size[targ]() == m.get_long_size()
42
43 import ctypes
44 assert m.get_size(ctypes.c_double(3.14)) == m.get_size['double']()
45 assert m.get_size(ctypes.c_double(3.14).value) == m.get_size['double']()+1
46
47 # auto-instantiation
48 assert m.get_size[float]() == m.get_float_size()
49 assert m.get_size['double']() == m.get_double_size()
50 assert m.get_size['MyTemplatedMethodClass']() == m.get_self_size()
51
52 # auto through typedef
53 assert m.get_size['MyTMCTypedef_t']() == m.get_self_size()
54 assert m.get_size['MyTemplatedMethodClass']() == m.get_self_size()
55
56 def test02_non_type_template_args(self):
57 """Use of non-types as template arguments"""
58
59 import _cppyy as cppyy
60
61 cppyy.gbl.gInterpreter.Declare("template<int i> int nt_templ_args() { return i; };")
62
63 assert cppyy.gbl.nt_templ_args[1]() == 1
64 assert cppyy.gbl.nt_templ_args[256]() == 256
65
66 def test03_templated_function(self):
67 """Templated global and static functions lookup and calls"""
68
69 import _cppyy as cppyy
70
71 # TODO: the following only works if something else has already
72 # loaded the headers associated with this template
73 ggs = cppyy.gbl.global_get_size
74 assert ggs['char']() == 1
75
76 gsf = cppyy.gbl.global_some_foo
77
78 assert gsf[int](3) == 42
79 assert gsf(3) == 42
80 assert gsf(3.) == 42
81
82 gsb = cppyy.gbl.global_some_bar
83
84 assert gsb(3) == 13
85 assert gsb['double'](3.) == 13
86
87 # TODO: the following only works in a namespace
88 nsgsb = cppyy.gbl.SomeNS.some_bar
89
90 assert nsgsb[3]
91 assert nsgsb[3]() == 3
92
93 # TODO: add some static template method
94
95 # test forced creation of subsequent overloads
96 vector = cppyy.gbl.std.vector
97 # float in, float out
98 ggsr = cppyy.gbl.global_get_some_result['std::vector<float>']
99 assert type(ggsr(vector['float']([0.5])).m_retval) == float
100 assert ggsr(vector['float']([0.5])).m_retval == 0.5
101 # int in, float out
102 ggsr = cppyy.gbl.global_get_some_result['std::vector<int>']
103 assert type(ggsr(vector['int']([5])).m_retval) == float
104 assert ggsr(vector['int']([5])).m_retval == 5.
105 # float in, int out
106 ggsr = cppyy.gbl.global_get_some_result['std::vector<float>, int']
107 assert type(ggsr(vector['float']([0.3])).m_retval) == int
108 assert ggsr(vector['float']([0.3])).m_retval == 0
109 # int in, int out
110 ggsr = cppyy.gbl.global_get_some_result['std::vector<int>, int']
111 assert type(ggsr(vector['int']([5])).m_retval) == int
112 assert ggsr(vector['int']([5])).m_retval == 5
113
114 def test04_variadic_function(self):
115 """Call a variadic function"""
116
117 import _cppyy as cppyy
118 std = cppyy.gbl.std
119
120 s = std.ostringstream('(', std.ios_base.ate)
121 # Fails; wrong overload on PyPy, none on CPython
122 #s << "("
123 cppyy.gbl.SomeNS.tuplify(s, 1, 4., "aap")
124 assert s.str() == "(1, 4, aap, NULL)"
125
126 cppyy.gbl.gInterpreter.Declare("""
127 template<typename... myTypes>
128 int test04_variadic_func() { return sizeof...(myTypes); }
129 """)
130
131 assert cppyy.gbl.test04_variadic_func['int', 'double', 'void*']() == 3
132
133 def test05_variadic_overload(self):
134 """Call an overloaded variadic function"""
135
136 import _cppyy as cppyy
137
138 assert cppyy.gbl.isSomeInt(3.) == False
139 assert cppyy.gbl.isSomeInt(1) == True
140 assert cppyy.gbl.isSomeInt() == False
141 assert cppyy.gbl.isSomeInt(1, 2, 3) == False
142
143 def test06_variadic_sfinae(self):
144 """Attribute testing through SFINAE"""
145
146 import _cppyy as cppyy
147 cppyy.gbl.AttrTesting # load
148 Obj1 = cppyy.gbl.AttrTesting.Obj1
149 Obj2 = cppyy.gbl.AttrTesting.Obj2
150 has_var1 = cppyy.gbl.AttrTesting.has_var1
151 call_has_var1 = cppyy.gbl.AttrTesting.call_has_var1
152
153 assert has_var1(Obj1()) == hasattr(Obj1(), 'var1')
154 assert has_var1(Obj2()) == hasattr(Obj2(), 'var1')
155 assert has_var1(3) == hasattr(3, 'var1')
156 assert has_var1("aap") == hasattr("aap", 'var1')
157
158 move = cppyy.gbl.std.move
159
160 assert call_has_var1(move(Obj1())) == True
161 assert call_has_var1(move(Obj2())) == False
162
163 def test07_type_deduction(self):
164 """Traits/type deduction"""
165
166 import _cppyy as cppyy
167 cppyy.gbl.AttrTesting # load
168 select_template_arg = cppyy.gbl.AttrTesting.select_template_arg
169 Obj1 = cppyy.gbl.AttrTesting.Obj1
170 Obj2 = cppyy.gbl.AttrTesting.Obj2
171
172 #assert select_template_arg[0, Obj1, Obj2].argument == Obj1
173 assert select_template_arg[1, Obj1, Obj2].argument == Obj2
174 raises(TypeError, select_template_arg.__getitem__, 2, Obj1, Obj2)
175
176 # TODO: the following only results in a Cling compilation error
177 #assert select_template_arg[1, int, float].argument == float
178
179 def test08_using_of_static_data(self):
180 """Derived class using static data of base"""
181
182 import _cppyy as cppyy
183
184 # TODO: the following should live in templates.h, but currently fails
185 # in TClass::GetListOfMethods()
186 cppyy.gbl.gInterpreter.Declare("""
187 template <typename T> struct BaseClassWithStatic {
188 static T const ref_value;
189 };
190
191 template <typename T>
192 T const BaseClassWithStatic<T>::ref_value = 42;
193
194 template <typename T>
195 struct DerivedClassUsingStatic : public BaseClassWithStatic<T> {
196 using BaseClassWithStatic<T>::ref_value;
197
198 explicit DerivedClassUsingStatic(T x) : BaseClassWithStatic<T>() {
199 m_value = x > ref_value ? ref_value : x;
200 }
201
202 T m_value;
203 };""")
204
205 assert cppyy.gbl.BaseClassWithStatic["size_t"].ref_value == 42
206
207 b1 = cppyy.gbl.DerivedClassUsingStatic["size_t"]( 0)
208 b2 = cppyy.gbl.DerivedClassUsingStatic["size_t"](100)
209
210 # assert b1.ref_value == 42
211 assert b1.m_value == 0
212
213 # assert b2.ref_value == 42
214 assert b2.m_value == 42
215
216 def test09_templated_callable(self):
217 """Test that templated operator() translates to __call__"""
218
219 import _cppyy as cppyy
220
221 tc = cppyy.gbl.TemplatedCallable()
222
223 assert tc(5) == 5.
224
225 def test10_templated_hidding_methods(self):
226 """Test that base class methods are not considered when hidden"""
227
228 import _cppyy as cppyy
229
230 B = cppyy.gbl.TemplateHiding.Base
231 D = cppyy.gbl.TemplateHiding.Derived
232
233 assert B().callme(1) == 2
234 assert D().callme() == 2
235 assert D().callme(2) == 2
236
237 def test11_templated_ctor(self):
238 """Test templated constructors"""
239
240 import _cppyy as cppyy
241
242 cppyy.gbl.gInterpreter.Declare("""
243 template <typename T>
244 class RTTest_SomeClassWithTCtor {
245 public:
246 template<typename R>
247 RTTest_SomeClassWithTCtor(int n, R val) : m_double(n+val) {}
248 double m_double;
249 };
250
251 namespace RTTest_SomeNamespace {
252
253 template <typename T>
254 class RTTest_SomeClassWithTCtor {
255 public:
256 RTTest_SomeClassWithTCtor() : m_double(-1.) {}
257 template<typename R>
258 RTTest_SomeClassWithTCtor(int n, R val) : m_double(n+val) {}
259 double m_double;
260 };
261
262 }
263 """)
264
265 gbl = cppyy.gbl
266
267 assert round(gbl.RTTest_SomeClassWithTCtor[int](1, 3.1).m_double - 4.1, 8) == 0.
268
269 RTTest2 = gbl.RTTest_SomeNamespace.RTTest_SomeClassWithTCtor
270 assert round(RTTest2[int](1, 3.1).m_double - 4.1, 8) == 0.
271 assert round(RTTest2[int]().m_double + 1., 8) == 0.
272
273 def test12_template_aliases(self):
274 """Access to templates made available with 'using'"""
275
276 import _cppyy as cppyy
277
278 # through dictionary
279 davec = cppyy.gbl.DA_vector["float"]()
280 davec += range(10)
281 assert davec[5] == 5
282
283 # through interpreter
284 cppyy.gbl.gInterpreter.Declare("template<typename T> using IA_vector = std::vector<T>;")
285 iavec = cppyy.gbl.IA_vector["float"]()
286 iavec += range(10)
287 assert iavec[5] == 5
288
289 # with variadic template
290 if cppyy.gbl.gInterpreter.ProcessLine("__cplusplus;") > 201402:
291 assert cppyy.gbl.using_problem.matryoshka[int, 3].type
292 assert cppyy.gbl.using_problem.matryoshka[int, 3, 4].type
293 assert cppyy.gbl.using_problem.make_vector[int , 3]
294 assert cppyy.gbl.using_problem.make_vector[int , 3]().m_val == 3
295 assert cppyy.gbl.using_problem.make_vector[int , 4]().m_val == 4
296
297 def test13_using_templated_method(self):
298 """Access to base class templated methods through 'using'"""
299
300 import _cppyy as cppyy
301
302 b = cppyy.gbl.using_problem.Base[int]()
303 assert type(b.get3()) == int
304 assert b.get3() == 5
305 assert type(b.get3['double'](5)) == float
306 assert b.get3['double'](5) == 10.
307
308 d = cppyy.gbl.using_problem.Derived[int]()
309 #assert type(d.get1['double'](5)) == float
310 #assert d.get1['double'](5) == 10.
311
312 assert type(d.get2()) == int
313 assert d.get2() == 5
314
315 assert type(d.get3['double'](5)) == float
316 assert d.get3['double'](5) == 10.
317 assert type(d.get3()) == int
318 assert d.get3() == 5
319
320 def test14_templated_return_type(self):
321 """Use of a templated return type"""
322
323 import _cppyy as cppyy
324
325 cppyy.gbl.gInterpreter.Declare("""
326 struct RTTest_SomeStruct1 {};
327 template<class ...T> struct RTTest_TemplatedList {};
328 template<class ...T> auto rttest_make_tlist(T ... args) {
329 return RTTest_TemplatedList<T...>{};
330 }
331
332 namespace RTTest_SomeNamespace {
333 struct RTTest_SomeStruct2 {};
334 template<class ...T> struct RTTest_TemplatedList2 {};
335 }
336
337 template<class ...T> auto rttest_make_tlist2(T ... args) {
338 return RTTest_SomeNamespace::RTTest_TemplatedList2<T...>{};
339 }
340 """)
341
342 rttest_make_tlist = cppyy.gbl.rttest_make_tlist
343 rttest_make_tlist2 = cppyy.gbl.rttest_make_tlist2
344 RTTest_SomeNamespace = cppyy.gbl.RTTest_SomeNamespace
345 RTTest_SomeStruct1 = cppyy.gbl.RTTest_SomeStruct1
346
347 assert rttest_make_tlist(RTTest_SomeStruct1())
348 assert rttest_make_tlist(RTTest_SomeNamespace.RTTest_SomeStruct2())
349 assert rttest_make_tlist2(RTTest_SomeStruct1())
350 assert rttest_make_tlist2(RTTest_SomeNamespace.RTTest_SomeStruct2())
351
352 def test15_rvalue_templates(self):
353 """Use of a template with r-values; should accept builtin types"""
354
355 import _cppyy as cppyy
356
357 is_valid = cppyy.gbl.T_WithRValue.is_valid
358
359 # bit of regression testing
360 assert is_valid(3)
361 assert is_valid['int'](3) # used to crash
362
363 # actual method calls
364 assert is_valid[int](1)
365 assert not is_valid(0)
366 assert is_valid(1.)
367 assert not is_valid(0.)
368
369 def test16_variadic(self):
370 """Range of variadic templates"""
371
372 import _cppyy as cppyy
373
374 ns = cppyy.gbl.some_variadic
375
376 def get_tn(ns):
377 # helper to make all platforms look the same
378 tn = ns.gTypeName
379 tn = tn.replace(' ', '')
380 tn = tn.replace('class', '')
381 tn = tn.replace('__cdecl', '')
382 tn = tn.replace('__thiscall', '')
383 tn = tn.replace('__ptr64', '')
384 return tn
385
386 # templated class
387 a = ns.A['int', 'double']()
388 assert get_tn(ns) == "some_variadic::A<int,double>"
389
390 # static functions
391 a.sa(1, 1., 'a')
392 assert get_tn(ns).find("some_variadic::A<int,double>::void(int&&,double&&,std::") == 0
393 ns.A['char&', 'double*'].sa(1, 1., 'a')
394 assert get_tn(ns).find("some_variadic::A<char&,double*>::void(int&&,double&&,std::") == 0
395 ns.A['char&', 'double*'].sa_T['int'](1, 1., 'a')
396 assert get_tn(ns).find("some_variadic::A<char&,double*>::int(int&&,double&&,std::") == 0
397
398 # member functions
399 a.a(1, 1., 'a')
400 assert get_tn(ns).find("void(some_variadic::A<int,double>::*)(int&&,double&&,std::") == 0
401 a.a_T['int'](1, 1., 'a')
402 assert get_tn(ns).find("int(some_variadic::A<int,double>::*)(int&&,double&&,std::") == 0
403
404 # non-templated class
405 b = ns.B()
406 assert get_tn(ns) == "some_variadic::B"
407
408 # static functions
409 b.sb(1, 1., 'a')
410 assert get_tn(ns).find("some_variadic::B::void(int&&,double&&,std::") == 0
411 ns.B.sb(1, 1., 'a')
412 assert get_tn(ns).find("some_variadic::B::void(int&&,double&&,std::") == 0
413 ns.B.sb_T['int'](1, 1., 'a')
414 assert get_tn(ns).find("some_variadic::B::int(int&&,double&&,std::") == 0
415
416 # member functions
417 b.b(1, 1., 'a')
418 assert get_tn(ns).find("void(some_variadic::B::*)(int&&,double&&,std::") == 0
419 b.b_T['int'](1, 1., 'a')
420 assert get_tn(ns).find("int(some_variadic::B::*)(int&&,double&&,std::") == 0
421
422 def test17_empty_body(self):
423 """Use of templated function with empty body"""
424
425 import _cppyy as cppyy
426
427 f_T = cppyy.gbl.T_WithEmptyBody.some_empty
428
429 assert cppyy.gbl.T_WithEmptyBody.side_effect == "not set"
430 assert f_T[int]() is None
431 assert cppyy.gbl.T_WithEmptyBody.side_effect == "side effect"
432
433 def test18_greedy_overloads(self):
434 """void*/void** should not pre-empt template instantiations"""
435
436 import _cppyy as cppyy
437
438 ns = cppyy.gbl.T_WithGreedyOverloads
439
440 # check that void* does not mask template instantiations
441 g1 = ns.WithGreedy1()
442 assert g1.get_size(ns.SomeClass(), True) == -1
443 assert g1.get_size(ns.SomeClass()) == cppyy.sizeof(ns.SomeClass)
444
445 # check that void* does not mask template instantiations
446 g2 = ns.WithGreedy2()
447 assert g2.get_size(ns.SomeClass()) == cppyy.sizeof(ns.SomeClass)
448 assert g2.get_size(ns.SomeClass(), True) == -1
449
450 # check that unknown classes do not mask template instantiations
451 g3 = ns.WithGreedy3()
452 assert g3.get_size(ns.SomeClass()) == cppyy.sizeof(ns.SomeClass)
453 assert g3.get_size(cppyy.nullptr, True) == -1
454
455 def test19_templated_operator_add(self):
456 """Templated operator+ is ambiguous: either __pos__ or __add__"""
457
458 import _cppyy as cppyy
459 gbl = cppyy.gbl
460
461 cppyy.gbl.gInterpreter.Declare("""
462 namespace OperatorAddTest {
463 template <class V>
464 class CustomVec {
465 V fX;
466 public:
467 CustomVec() : fX(0) {}
468 CustomVec(const V & a) : fX(a) { }
469 V X() const { return fX; }
470 template <class fV> CustomVec operator + (const fV& v) {
471 CustomVec<V> u;
472 u.fX = fX + v.fX;
473 return u;
474 }
475 }; }
476 """)
477
478 c = gbl.OperatorAddTest.CustomVec['double'](5.3)
479 d = gbl.OperatorAddTest.CustomVec['int'](1)
480
481 q = c + d
482
483 assert round(q.X() - 6.3, 8) == 0.
484
485 def test20_templated_ctor_with_defaults(self):
486 """Templated constructor with defaults used to be ignored"""
487
488 import _cppyy as cppyy
489
490 cppyy.gbl.gInterpreter.Declare(r"""
491 namespace TemplatedCtor { class C {
492 public:
493 template <typename Integer, typename std::enable_if_t<std::is_integral_v<Integer>, int> = 0>
494 C(Integer) {}
495 C(const std::string&) {}
496 }; }
497 """)
498
499 assert cppyy.gbl.TemplatedCtor.C(0)
500
501 def test21_type_deduction_with_conversion(self):
502 """Template instantiation with [] -> std::vector conversion"""
503
504 import _cppyy as cppyy
505
506 cppyy.gbl.gInterpreter.Declare("""
507 namespace l2v {
508 struct Base {};
509 struct Derived : Base {};
510
511 int test1(const std::vector<Base*>& v) { return (int)v.size(); }
512
513 template <typename T>
514 int test2(const std::vector<Derived*>& v) { return (int)v.size(); }
515
516 template <typename T>
517 int test2a(std::vector<Derived*> v) { return v.size(); }
518
519 template <typename T>
520 int test3(const std::vector<Base*>& v) { return (int)v.size(); }
521 }""")
522
523 l2v = cppyy.gbl.l2v
524
525 d1 = l2v.Derived()
526
527 assert l2v.test1([d1]) == 1
528 assert l2v.test1([d1, d1]) == 2
529
530 assert l2v.test2[int]([d1]) == 1
531 assert l2v.test2[int]([d1, d1]) == 2
532
533 assert l2v.test2a[int]([d1]) == 1
534 assert l2v.test2a[int]([d1, d1]) == 2
535
536 assert l2v.test3[int]([d1]) == 1
537 assert l2v.test3[int]([d1, d1]) == 2
538
539 def test22_type_deduction_of_proper_integer_size(self):
540 """Template type from integer arg should be big enough"""
541
542 import _cppyy as cppyy
543
544 cppyy.gbl.gInterpreter.Declare("template <typename T> T PassSomeInt(T t) { return t; }")
545
546 PassSomeInt = cppyy.gbl.PassSomeInt
547
548 for val in [1, 100000000000, -2**32, 2**32-1, 2**64-1 -2**63]:
549 assert val == PassSomeInt(val)
550
551 for val in [2**64, -2**63-1]:
552 raises(OverflowError, PassSomeInt, val)
553
554 def test23_overloaded_setitem(self):
555 """Template with overloaded non-templated and templated setitem"""
556
557 import _cppyy as cppyy
558
559 MyVec = cppyy.gbl.TemplateWithSetItem.MyVec
560
561 v = MyVec["float"](2)
562 v[0] = 1 # used to throw TypeError
563
564 def test24_stdfunction_templated_arguments(self):
565 """Use of std::function with templated arguments"""
566
567 import _cppyy as cppyy
568
569 def callback(x):
570 return sum(x)
571
572 cppyy.gbl.gInterpreter.Declare("""double callback_vector(
573 const std::function<double(std::vector<double>)>& callback, std::vector<double> x) {
574 return callback(x);
575 }""")
576
577 assert cppyy.gbl.std.function['double(std::vector<double>)']
578
579 assert cppyy.gbl.callback_vector(callback, [1, 2, 3]) == 6
580
581 cppyy.gbl.gInterpreter.Declare("""double wrap_callback_vector(
582 double (*callback)(std::vector<double>), std::vector<double> x) {
583 return callback_vector(callback, x);
584 }""")
585
586 assert cppyy.gbl.wrap_callback_vector(callback, [4, 5, 6]) == 15
587
588 assert cppyy.gbl.std.function['double(std::vector<double>)']
589
590 def test25_partial_templates(self):
591 """Deduction of types with partial templates"""
592
593 import _cppyy as cppyy
594
595 cppyy.gbl.gInterpreter.Declare("""\
596 template <typename A, typename B>
597 B partial_template_foo1(B b) { return b; }
598
599 template <typename A, typename B>
600 B partial_template_foo2(B b) { return b; }
601
602 namespace partial_template {
603 template <typename A, typename B>
604 B foo1(B b) { return b; }
605
606 template <typename A, typename B>
607 B foo2(B b) { return b; }
608 }
609 """)
610
611 ns = cppyy.gbl.partial_template
612
613 assert cppyy.gbl.partial_template_foo1['double', 'int'](17) == 17
614 assert cppyy.gbl.partial_template_foo1['double'](17) == 17
615
616 assert cppyy.gbl.partial_template_foo1['double'](17) == 17
617 assert cppyy.gbl.partial_template_foo1['double', 'int'](17) == 17
618
619 assert ns.foo1['double', 'int'](17) == 17
620 assert ns.foo1['double'](17) == 17
621
622 assert ns.foo2['double'](17) == 17
623 assert ns.foo2['double', 'int'](17) == 17
624
625 cppyy.gbl.gInterpreter.Declare("""\
626 template <typename A, typename... Other, typename B>
627 B partial_template_bar1(B b) { return b; }
628
629 template <typename A, typename... Other, typename B>
630 B partial_template_bar2(B b) { return b; }
631
632 namespace partial_template {
633 template <typename A, typename... Other, typename B>
634 B bar1(B b) { return b; }
635
636 template <typename A, typename... Other, typename B>
637 B bar2(B b) { return b; }
638 }""")
639
640 assert cppyy.gbl.partial_template_bar1['double','int'](17) == 17
641 assert cppyy.gbl.partial_template_bar1['double'](17) == 17
642
643 assert cppyy.gbl.partial_template_bar2['double'](17) == 17
644 assert cppyy.gbl.partial_template_bar2['double','int'](17) == 17
645
646 assert ns.bar1['double','int'](17) == 17
647 assert ns.bar1['double'](17) == 17
648
649 assert ns.bar2['double'](17) == 17
650 assert ns.bar2['double','int'](17) == 17
651
652 def test26_variadic_constructor(self):
653 """Use of variadic template function as contructor"""
654
655 import _cppyy as cppyy
656
657 cppyy.gbl.gInterpreter.Declare("""\
658 namespace VadiadicConstructor {
659 class Atom {
660 public:
661 using mass_type = double;
662
663 Atom() {}
664
665 template<typename... Args>
666 explicit Atom(const mass_type& mass_in, Args&&... args) :
667 Atom(std::forward<Args>(args)...) {
668 constexpr bool is_mass =
669 std::disjunction_v<std::is_same<std::decay_t<Args>, mass_type>...>;
670 static_assert(!is_mass, "Please only provide one mass");
671 mass() = mass_in;
672 }
673
674 mass_type& mass() noexcept {
675 return m_m;
676 }
677
678 mass_type m_m = 0.0;
679 }; }""")
680
681 ns = cppyy.gbl.VadiadicConstructor
682
683 a = ns.Atom(1567.0)
684 assert a.m_m == 1567.0
685
686 def test27_enum_in_constructor(self):
687 """Use of enums in template function as constructor"""
688
689 import _cppyy as cppyy
690
691 cppyy.gbl.gInterpreter.Declare("""\
692 namespace EnumConstructor {
693 struct ST {
694 enum TI { I32 };
695 };
696
697 struct FS {
698 enum R { EQ, NE, GT, GE, LT, LE };
699
700 template<typename T>
701 FS(const std::string&, const ST::TI, R, const T&e) {}
702 }; }""")
703
704 ns = cppyy.gbl.EnumConstructor
705
706 assert ns.FS('i', ns.ST.I32, ns.FS.EQ, 10)
707 assert ns.FS('i', ns.ST.TI.I32, ns.FS.R.EQ, 10)
708
709
710 class AppTestTEMPLATED_TYPEDEFS:
711 spaceconfig = dict(usemodules=['_cppyy', '_rawffi', 'itertools'])
712
713 def setup_class(cls):
714 cls.w_test_dct = cls.space.newtext(test_dct)
715 cls.w_templates = cls.space.appexec([], """():
716 import ctypes, _cppyy
717 _cppyy._post_import_startup()
718 return ctypes.CDLL(%r, ctypes.RTLD_GLOBAL)""" % (test_dct, ))
719
720 def test01_using(self):
721 """Test presence and validity of using typededs"""
722
723 import _cppyy as cppyy
724
725 tct = cppyy.gbl.TemplatedTypedefs.DerivedWithUsing
726 dum = cppyy.gbl.TemplatedTypedefs.SomeDummy
727
728 assert tct[int, dum, 4].vsize == 4
729 assert tct[int, dum, 8].vsize == 8
730
731 in_type = tct[int, dum, 4].in_type
732 assert 'in_type' in dir(tct[int, dum, 4])
733
734 assert in_type.__name__ == 'in_type'
735 assert in_type.__cpp_name__ == 'TemplatedTypedefs::DerivedWithUsing<int,TemplatedTypedefs::SomeDummy,4>::in_type'
736
737 in_type_tt = tct[int, dum, 4].in_type_tt
738 assert 'in_type_tt' in dir(tct[int, dum, 4])
739
740 assert in_type_tt.__name__ == 'in_type_tt'
741 assert in_type_tt.__cpp_name__ == 'TemplatedTypedefs::DerivedWithUsing<int,TemplatedTypedefs::SomeDummy,4>::in_type_tt'
742
743 def test02_mapped_type_as_internal(self):
744 """Test that mapped types can be used as builting"""
745
746 import _cppyy as cppyy
747 tct = cppyy.gbl.TemplatedTypedefs.DerivedWithUsing
748 dum = cppyy.gbl.TemplatedTypedefs.SomeDummy
749
750 for argname in ['short', 'unsigned short', 'int']:
751 in_type = tct[argname, dum, 4].in_type
752 assert issubclass(in_type, int)
753 assert in_type(13) == 13
754 assert 2*in_type(42) - 84 == 0
755
756 for argname in ['unsigned int', 'long', 'unsigned long']:# TODO: 'long long', 'unsigned long long'
757 in_type = tct[argname, dum, 4].in_type
758 assert issubclass(in_type, pylong)
759 assert in_type(13) == 13
760 assert 2*in_type(42) - 84 == 0
761
762 for argname in ['float', 'double', 'long double']:
763 in_type = tct[argname, dum, 4].in_type
764 assert issubclass(in_type, float)
765 assert in_type(13) == 13.
766 assert 2*in_type(42) - 84. == 0.
767
768 raises(TypeError, tct.__getitem__, 'gibberish', dum, 4)
769
770 def test03_mapped_type_as_template_arg(self):
771 """Test that mapped types can be used as template arguments"""
772
773 import _cppyy as cppyy
774
775 tct = cppyy.gbl.TemplatedTypedefs.DerivedWithUsing
776 dum = cppyy.gbl.TemplatedTypedefs.SomeDummy
777
778 in_type = tct['unsigned int', dum, 4].in_type
779 assert tct['unsigned int', dum, 4] is tct[in_type, dum, 4]
780
781 in_type = tct['long double', dum, 4].in_type
782 assert tct['long double', dum, 4] is tct[in_type, dum, 4]
783 assert tct['double', dum, 4] is not tct[in_type, dum, 4]
784
785 def test04_type_deduction(self):
786 """Usage of type reducer"""
787
788 import _cppyy as cppyy
789
790 cppyy.gbl.gInterpreter.Declare("""
791 template <typename T> struct DeductTest_Wrap {
792 static auto whatis(T t) { return t; }
793 };
794 """)
795
796 w = cppyy.gbl.DeductTest_Wrap[int]()
797 three = w.whatis(3)
798 assert three == 3
799
800 def test05_type_deduction_and_extern(self):
801 """Usage of type reducer with extern template"""
802
803 import _cppyy as cppyy
804 import sys
805
806 cppyy.gbl.gInterpreter.Declare("""\
807 namespace FailedTypeDeducer {
808
809 template<class T>
810 class A {
811 public:
812 T result() { return T{5}; }
813 };
814
815 extern template class A<int>;
816 }""")
817
818 if sys.platform != 'darwin': # feature disabled
819 assert cppyy.gbl.FailedTypeDeducer.A[int]().result() == 42
820 assert cppyy.gbl.FailedTypeDeducer.A['double']().result() == 5.
821
822 # FailedTypeDeducer::B is defined in the templates.h header
823 assert cppyy.gbl.FailedTypeDeducer.B['double']().result() == 5.
824 assert cppyy.gbl.FailedTypeDeducer.B[int]().result() == 5
825
826
827 class AppTestTEMPLATE_TYPE_REDUCTION:
828 spaceconfig = dict(usemodules=['_cppyy', '_rawffi', 'itertools'])
829
830 def setup_class(cls):
831 cls.w_test_dct = cls.space.newtext(test_dct)
832 cls.w_templates = cls.space.appexec([], """():
833 import ctypes, _cppyy
834 _cppyy._post_import_startup()
835 return ctypes.CDLL(%r, ctypes.RTLD_GLOBAL)""" % (test_dct, ))
836
837 def test01_reduce_binary(self):
838 """Squash template expressions for binary operations (like in gmpxx)"""
839
840 import _cppyy as cppyy
841
842 e1 = cppyy.gbl.TypeReduction.Expr[int]()
843 e2 = cppyy.gbl.TypeReduction.Expr[int]()
844
845 cppyy.py.add_type_reducer('TypeReduction::BinaryExpr<int>', 'TypeReduction::Expr<int>')
846
847 assert type(e1+e2) == cppyy.gbl.TypeReduction.Expr[int]