English 中文(简体)
Boost.Python: Defining a constructor outside a class
原标题:

Given a class:

class TCurrency {
    TCurrency();
    TCurrency(long);
    TCurrency(const std::string);
    ...
};

Wrapped with Boost.Python:

class_<TCurrency>( "TCurrency" )
    .def( init<long> )
    .def( init<const std::string&> )
    ...
    ;

Is it possible to create a factory method that appears as a constructor in Python:

TCurrency TCurrency_from_Foo( const Foo& ) { return TCurrency(); }

Such that in python:

bar = TCurrency(foo)
最佳回答

You can use make_constructor (untested):

TCurrency* TCurrency_from_Foo( const Foo& ) { return new TCurrency(); }

class_<TCurrency>( "TCurrency" )
    .def( "__init__", boost::python::make_constructor( &TCurrency_from_Foo) )
;

The argument to make_constructor is any functor that returns a pointer[1] to the wrapped class.

[1] Actually, the function must return a the pointer holder type, so if your pointer holder is boost::shared_ptr, the function should return a boost::shared_ptr instead of a raw pointer.

问题回答

May be my example helps you - init_python_object function can take any parameters that you need. Simple note: I define class_t with boost::noncopyable and no_init.





相关问题
UserControl constructor with parameters in C#

Call me crazy, but I m the type of guy that likes constructors with parameters (if needed), as opposed to a constructor with no parameters followed by setting properties. My thought process: if the ...

Strange "type class::method() : stuff " syntax C++

While reading some stuff on the pImpl idiom I found something like this: MyClass::MyClass() : pimpl_( new MyClassImp() ) First: What does it mean? Second: What is the syntax? Sorry for being such ...

Anonymous class question

I ve a little doubt over this line: An anonymous class cannot define a constructor then, why we can also define an Anonymous class with the following syntax: new class-name ( [ argument-list ] ) {...

Why copy constructor is not called in this case?

Here is the little code snippet: class A { public: A(int value) : value_(value) { cout <<"Regular constructor" <<endl; } A(const A& other) : value_(other....

Invoking an instance method without invoking constructor

Let s say I have the following class which I am not allowed to change: public class C { public C() { CreateSideEffects(); } public void M() { DoSomethingUseful(); } } and I have to call M ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

热门标签