【问题标题】:How can I wrap a variadic template member function of a variadic template class in SWIG?如何在 SWIG 中包装可变参数模板类的可变参数模板成员函数?
【发布时间】:2019-12-20 22:15:41
【问题描述】:

我有一个包含可变参数模板定义的头文件,其中还包含一些可变参数模板化成员函数。为了简洁起见,下面的代码 sn-ps 已大大简化和删减:

#pragma once

template<typename T, typename ... CtorArgs>
class Foo {
public:
  Foo(CtorArgs... args) : _m(args...) {}

  template<typename ... Args>
  void DoSomething(Args... args) { _m.DoSomething(args...); }
private:
  T _m;
};

然后我有另一个头文件定义了要在模板特化中使用的类:

#pragma once

#include <string>
#include <iostream>

class Bar {
public:
  Bar(std::string const & a,
      std::string const & b) :
        m_strA(a),
        m_strB(b) {}

  void DoSomething(int const one, int const two) {
    std::cout << "Str A: " << m_strA << ", Str B: "<<  m_strB << ", ints: " << one << ", " << two << std::endl;
  }

private:
  std::string m_strA;
  std::string m_strB;
};

我想使用 SWIG 封装 Foo 特化,以及它的模板化成员函数,以便我可以从 Lua 脚本中使用它们。

我遇到的问题是 SWIG 没有像我预期的那样为 DoSomething 模板化函数生成包装器。

在阅读了一些 SWIG 文档后,我知道它无法使用 %template 指令来替换参数包参数超过 1 个,因此我使用了 %改为重命名

%module FooSwig
%include <std_string.i>

%{
#include "foo.hpp"
#include "bar.hpp"
%}

%include "foo.hpp"
%include "bar.hpp"

%rename(lua_foo) Foo<Bar, std::string const &, std::string const &>;
class Foo<Bar, std::string const &, std::string const &> {
public:
  Foo(std::string const &, std::string const &);

  template<typename ... Args>
  void DoSomething(Args... args);
private:
  Bar _m;
};

使用 %template 指令不起作用(如预期的那样),因为要替换的参数超过 1 个 - 我从 swig 得到以下信息:

错误:模板“DoSomething”未定义。

我想我需要再次使用 %rename 来解决这个问题,但我不知道该怎么做。我尝试了以下方法:

%extend Foo<Bar, std::string const &, std::string const &>
{
  %rename(Do_Something) DoSomething<int const, int const>;
  void DoSomething(int const, int const);
}

这确实会产生一些东西,但是包装器包含一个未定义函数的符号:

Foo_Sl_Bar_Sc_std_string_SS_const_SA__Sc_std_string_SS_const_SA__Sg__DoSomething(arg1,arg2,arg3);

而不是对成员函数模板的预期调用,类似于

(arg1)->SWIGTEMPLATEDISAMBIGUATOR DoSomething<int const, int const>(arg2, arg3);

我没有什么可以尝试的了,也许你们中的一个可以帮忙?

关于我的环境的一些信息: 我正在使用 g++ 7.4.0、c++ 17 和 SWIG 3.0。

【问题讨论】:

    标签: c++ templates lua variadic-templates swig


    【解决方案1】:

    我设法生成了包装器,它按预期工作。

    这是旧 SWIG 接口文件的 sn-p:

    ...
      template<typename ... Args>
      void DoSomething(Args... args);
    ...
    

    我将其替换为以下内容:

    ...
      void DoSomething(int const, int const);
    ...
    

    但是我仍然很想知道是否有更好的方法可以做到这一点,因此任何进一步的信息(或阅读材料/源代码的指针)将不胜感激。

    【讨论】:

    • 这当然是最简单的解决方案,也是我要推荐的解决方案。
    【解决方案2】:

    我想出的最好的解决方法是编写多个模板类,每个模板类都有不同数量的模板参数,因为通常它们并不多。

    【讨论】:

    • 看起来像是评论而不是答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多