【问题标题】:How to instantiate a template method of a template class with swig?如何用 swig 实例化模板类的模板方法?
【发布时间】:2013-04-25 15:32:37
【问题描述】:

我在 C++ 中有一个类,它是一个模板类,并且这个类的一个方法模板化在另一个占位符上

template <class T>
class Whatever {
public:
    template <class V>
    void foo(std::vector<V> values);
}

当我将这个类传输到 swig 文件时,我做到了

%template(Whatever_MyT) Whatever<MyT>;

不幸的是,当我尝试在 python 的 What_MyT 实例上调用 foo 时,出现属性错误。我以为我必须用

实例化成员函数
%template(foo_double) Whatever<MyT>::foo<double>;

这是我会用 C++ 编写的,但它不起作用(我收到语法错误)

问题出在哪里?

【问题讨论】:

    标签: c++ python swig


    【解决方案1】:

    先声明成员模板的实例,再声明类模板的实例。

    示例

    %module x
    
    %inline %{
    #include<iostream>
    template<class T> class Whatever
    {
        T m;
    public:
        Whatever(T a) : m(a) {}
        template<class V> void foo(V a) { std::cout << m << " " << a << std::endl; }
    };
    %}
    
    // member templates
    // NOTE: You *can* use the same name for member templates,
    //       which is useful if you have a lot of types to support.
    %template(fooi) Whatever::foo<int>;
    %template(food) Whatever::foo<double>;
    // class templates.  Each will contain fooi and food members.
    // NOTE: You *can't* use the same template name for the classes.
    %template(Whateveri) Whatever<int>;
    %template(Whateverd) Whatever<double>;
    

    输出

    >>> import x
    >>> wi=x.Whateveri(5)
    >>> wd=x.Whateverd(2.5)
    >>> wi.fooi(7)
    5 7
    >>> wd.fooi(7)
    2.5 7
    >>> wi.food(2.5)
    5 2.5
    >>> wd.food(2.5)
    2.5 2.5
    

    参考:在SWIG 2.0 Documentation6.18 Templates(搜索“会员模板”)。

    【讨论】:

    • 它工作得非常好,但是你如何实例化多个实例的成员函数,比如 What::foo 和 What::foo。对我来说,它总是以后者结束。
    • @JensMunk,你确定给每个%template 一个不同的唯一名称吗?
    • 不幸的是,这不是错误。我使用的是旧版本的 SWIG,所以我不会对此发表进一步评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多