pythonc++python-c-apicppyy

Type alias arguments in cppyy


I'm trying to use some C++ libraries in Python code. One issue I've had is I can't seem to call functions that take an aliased type as an argument. Here is a minimal example I've reproduced:

import cppyy

cppyy.cppdef(
    """
using namespace std;

enum class TestEnum
{
    Foo,
    Bar
};

using TestDictClass = initializer_list<pair< TestEnum, int>>;

class TestClass {
public:
    TestClass(TestDictClass x);
};
"""
)

from cppyy.gbl.std import pair
from cppyy.gbl import TestEnum, TestDictClass, TestClass

TestPair = pair[TestEnum, int]
arg = TestDictClass([TestPair(TestEnum.Bar, 4), TestPair(TestEnum.Foo, 12)])
print("Arg is:")
print(arg)
print("\n")
print("Res is:")
res = TestClass(arg)
print(res)

This gives the output:

Arg is:
<cppyy.gbl.std.initializer_list<std::pair<TestEnum,int> > object at 0x09646008>


Res is:
Traceback (most recent call last):
  File ".\scratch\test-alias.py", line 31, in <module>
    res = TestClass(arg)
TypeError: none of the 3 overloaded methods succeeded. Full details:
  TestClass::TestClass(TestDictClass x) =>
    TypeError: could not convert argument 1
  TestClass::TestClass(TestClass&&) =>
    ValueError: could not convert argument 1 (object is not an rvalue)
  TestClass::TestClass(const TestClass&) =>
    TypeError: could not convert argument 1

Please note my C++ experience is quite limited. Is the issue the type alias, or something else? If it's the type conversion, how can I work around this?


Solution

  • The problem is not with the alias, just that the converter code is not expecting an explicit std::initializer_list object, only the implicit conversions. This will work:

    res = TestClass([TestPair(TestEnum.Bar, 4), TestPair(TestEnum.Foo, 12)])
    

    Edit: cppyy with repo master, the above now works as well.