从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明

SWIG error when inheriting from partially-specified template class with defaults, with forward declaration without defaults

本文关键字:默认值 错误 SWIG 声明 继承      更新时间:2023-10-16

我在尝试为要使用的库生成SWIG接口时出错。该代码包含一个从模板化类继承的类,该类包含默认值。但是,模板化类也有一个不包含默认值的正向声明。我相信这是令人困惑的swig。

这里有一个简单的例子:

frac.h(父类(:

#pragma once
// forward declaration
template <typename A, typename B>
class Frac;
// ... code using the forward declaraton
// definition
template <typename A=int, typename B=int>
class Frac
{
public:
A a;
B b;
double divide()
{
return a / b;
};
};

timestwo.h(子类(:

#pragma once
#include "frac.h"
class TimesTwo : public Frac<double>
{
public:
double getValue()
{
a = 10.5;
b = 4;
return divide() * 2;
}
};

mylib.i文件:

%module mylib
%{
#include "timestwo.h"
%}
%include "frac.h"
/*
If no %template is used:
mylib.h:15: Warning 401: Nothing known about base class 'Frac< double >'. Ignored.
mylib.h:15: Warning 401: Maybe you forgot to instantiate 'Frac< double >' using %template.
*/
/*
If put here: %template(frac_d) Frac <double>;
mylib.i:15: Error: Not enough template parameters specified. 2 required.
*/
/*
If put here: %template(frac_d) Frac <double, int>;
timestwo.h:5: Warning 401: Nothing known about base class 'Frac< double >'. Ignored.
timestwo.h:5: Warning 401: Maybe you forgot to instantiate 'Frac< double >' using %template.
*/
%include "timestwo.h"

mylib.i的注释所示,我似乎无法正确实例化模板,因为我需要使用一个模板参数,但由于forward声明没有指定默认值,它表示需要两个。

这只是一个警告。您想实例化Frac还是调用divide?否则,它会起作用:

>>> import mylib
>>> t = mylib.TimesTwo()
>>> t.getValue()
5.25

如果您想调用divide(),SWIG似乎不了解模板默认值。它通过用Frac<double,int>更新timestwo.h来工作,但如果你不想修改头,你可以手动复制.i文件中的定义,并更正:

%module mylib
%{
#include "timestwo.h"
%}
%include "frac.h"
%template(frac_d) Frac<double,int>; // Frac<double> doesn't work as of SWIG 3.0.12.
// Declare the interface the way SWIG likes it.
class TimesTwo : public Frac<double,int>
{
public:
double getValue();
};

演示:

>>> import mylib
>>> t = mylib.TimesTwo()
>>> t.getValue()
5.25
>>> t.divide()
2.625