用swig包装专门的c ++模板类

时间:2012-03-18 10:39:49

标签: c++ templates swig

考虑以下类声明:

namespace X {
template<class T>
class Foo {
public:
    Foo();
    virtual ~Foo();

    T value() const;
};

template<class T>
class Foo<vector<T>> {
public:
    Foo();
    virtual ~Foo();

    T value( const int ) const;
};
}

对于他们我在foo.i文件中有以下声明

%include "stl.i"
%include "std_string.i"
%include "std_vector.i"

namespace X {
using namespace std;

template<class T>
class Foo {
public:
    Foo();
    virtual ~Foo();
    T value() const;
};

template<class T>
class Foo<vector<T> > {
public:
    Foo();
    virtual ~Foo();
    T value( const int ) const;
};

%template(FooInt) Foo<int>;
%template(FooString) Foo<string>;
%template(FooVectorInt) Foo<vector<int> >;

}

两个类之间的区别在于后者向量容器的特化和 value()方法的不同签名,其中第一个不带参数,而第二个带有期望值整数。

由swig组合的包装器代码将%template(FooVectorInt)错误包装起来,因为它调用value()方法而不是专用向量方法value(const int)。给我以下编译错误消息:

foo_wrap.cxx: in function »int _wrap_FooVectorInt_value(lua_State*)«:

/home/noobsaibot/foo/bindings/src/lua/foo_wrap.cxx:6706:81: error: no matching function to call »X::Foo<std::vector<int> >::value() const«
/home/noobsaibot/foo/src/foo.h:78:5: note: candidate is: T X::Foo<std::vector<_RealType> >::value(int) const [with T = int, int = unsigned int]

任何关于我可能缺少什么的建议让swig明白哪个函数是正确的?

欢呼声

1 个答案:

答案 0 :(得分:4)

您可以通过以下方式获得所需的结果:

%include "stl.i"
%include "std_string.i"
%include "std_vector.i"

namespace X {
using namespace std;

%rename(FooVectorInt) Foo<std::vector<int> >;

class Foo<std::vector<int> > {
public:
    virtual ~Foo();
    int value( const int ) const;
};

template<class T>
class Foo {
public:
    Foo();
    virtual ~Foo();
    T value() const;
};

%template(FooInt) Foo<int>;
%template(FooString) Foo<string>;
}

这是有效的,因为您在接口文件中编写的内容不是 C ++,重要的是SWIG会生成正确的代码。如果你想重复这个批次,你可以编写宏(它接近于%template)。

这仍然不是一个非常干净的解决方案 - 我希望这与专业化“正常工作”,我也看不到更简单的解决方法。