【发布时间】: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