%扩展标签和模板方法

时间:2015-08-15 14:46:31

标签: c++ templates swig extends

我在C ++方面有非模板类是否可以使用模板方法扩展它?到目前为止,它对我没用。

我试过

%extend A {

  template <typename T>
  void fn(T t) {
    // some common code 
  }
}

%template (Afni) A::fn<int>;
...;

但是{c}文件中没有以这种方式生成A::fn<int>

所以我必须使用

%extend A {

  void fn(int t) {
    // some common code 
  }
  ...
}
这种方法的缺点是重复相同的通用代码。

1 个答案:

答案 0 :(得分:0)

SWIG必须知道如何翻译模板类型。默认情况下未翻译的每种类型都应使用%typemap为SWIG定义。关于%extend,它应该如下工作:

//This is for compiling cxx as an ordinary cpp
%header %{
#include "class_header.h"
}

//OriginalClass is defined in the "class_header.h".
//So, it is already known to SWIG but not declared as the destination class.
//Here is the class definition for the destination code.
//All members defined in it supported by SWIG with the appropriate proxying code.
class OriginalClass {
    //Here you may declare all the members you want to access in the destination code
    inline const some_internal_type & get_data() const;
    //some_internal_type is assumed known to SWIG after declaring it with %typemap for in/out converting

    //Here is the whole block extending OriginalClass
    %extend {
        template<class T>
        void fn(T t) {
        }

        void setup(other_data p_dest) {
        //There is no the setup member in OriginalClass, but this method is available for the destination code
        //other_data is typemapped somewhere above for SWIG using %typemap
        }
    }
};

对于每个被替换的T进入fn,SWIG应该提供适当的%typemap,以便在代理代码中表示T