【问题标题】:SWIG error when inheriting from partially-specified template class with defaults, with forward declaration without defaults从具有默认值的部分指定模板类继承时出现 SWIG 错误,前向声明没有默认值
【发布时间】:2018-10-26 13:30:28
【问题描述】:

我在尝试为我想使用的库生成 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 的 cmets 所示,我似乎无法正确实例化模板,因为我需要使用一个模板参数,但由于前向声明没有指定默认值,它说它期待两个.

【问题讨论】:

    标签: c++ swig


    【解决方案1】:

    这只是一个警告。是要实例化Frac 还是调用divide?否则,它可以工作:

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

    如果您希望能够调用 divide(),SWIG 似乎无法理解模板默认值。它通过使用Frac&lt;double,int&gt; 更新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
    

    【讨论】:

    • 接受这个工作,但这并不理想。真正的timestwo.h 是库的一部分,因此我无法更改它,并且它包含许多其他需要的定义,因此将所有内容复制到此.i 文件中并不理想,以防将来发生更改。跨度>
    • @Stanley Swig c++ 解析器尚未达到最新标准。
    猜你喜欢
    • 2010-12-20
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    相关资源
    最近更新 更多