具有私有/删除默认构造函数的参数类型

时间:2014-07-21 00:38:47

标签: c++ swig

我想说我想在SWIG中输入std::type_index作为参数(忽略目标语言中所述类型的完全无意义)。

void dosomething(std::type_index arg);

在使用类型图方法(如inarginit生成代码之前,包装此函数会在生成的代码中提供以下decldef:

std::type_index arg1;

std::type_index没有默认构造函数。我无法访问其定义。 C ++编译器毫不客气地拒绝代码。

如何让SWIG生成可用的代码?

我查看了不同的typemap方法,什么也没找到;特别是,typemap(arginit)看起来很有希望,但是当它没有取代arg1的decldef时就失败了。

更新:将功能签名更改为...

void dosomething(const std::type_index& arg);

...强制SWIG生成std::type_index*作为arg1类型。尽管如此,我仍然可以通过传递值来解决这个问题。我的原始问题代表(在一个四重否定的池中)。

修改

对于每个请求,一个函数从Python调用一个函数的方式,该函数用一个由SWIG按类型映射到std::type_index的Python字符串看起来如下:

dosomething("ClassName")

2 个答案:

答案 0 :(得分:1)

我不太了解SWIG,所以我在这里描述的是一般解决方案。如果您确实需要默认构造函数,则必须创建一个包装类,例如

class TypeIndex {  // C++11
public:
   TypeIndex() { }
   TypeIndex(...): m(new std::type_index(...)) { }
   ~TypeIndex() { delete m; }
   TypeIndex(const TypeIndex &other)
   {
       if (other.m)
           m = new std::type_index(*other.m);
   }
   TypeIndex &operator = (const TypeIndex &rhs) 
   {
       if (!m && !rhs.m)
           return *this;
       if (this != rhs.m) {
           delete m;
           if (!rhs.m)
               m = nullptr;
           else
               m = new std::type_index(*rhs.m);
       }
       return *this;
   }
// and implement wrapping functions as you need, for instance...
   size_t hash_code() const { return m ? m->hash_code() : 0; }
private:
   std::type_index *m = nullptr;
};

更简单但有潜在危险的方法是继承std::type_index。在这种情况下,您只需要默认构造函数TypeIndex() {}。请注意std::type_index没有虚拟析构函数,因此在需要多态时它不会安全。

答案 1 :(得分:1)

使用%nodefaultctor功能:

%nodefaultctor std::type_index;  // Disable default constructor generation for that class

由于std::type_index没有定义默认构造函数,所以这应该有效。看起来你必须在.i文件中定义类之前放置语句,所以在%include的{​​{1}}语句之前。

SWIG文档的第6.6.2节中的删除(例如http://www.swig.org/Doc3.0/SWIGPlus.html#SWIGPlus_nn8如果您使用的是SWIG 3 - 但此功能自1.3以来没有太大变化)。

更新:如果您的目标是将该功能调用为type_index,那么我会考虑使用dosomething("ClassName")创建%inline,然后调用dosomething(std::string)版本。它会在你的.i文件中看起来像这样:

type_index
相关问题