7 SWIG and C++0x

7.1 Introduction

This chapter gives you a brief overview about the SWIG implementation of the C++0x standard. This part of SWIG is still a work in progress. Initial C++0x support for SWIG was written during the Google Summer of Code 2009 period.

SWIG supports all the new C++ syntax changes with some minor limitations (decltype expressions, variadic templates number). Wrappers for the new STL types (unordered_ containers, result_of, tuples) are not supported yet.

7.2 Core language changes

7.2.1 Rvalue reference and move semantics

SWIG correctly parses the new operator && the same as the reference operator &.

The wrapper for the following code is correctly produced:

class MyClass {
  MyClass(MyClass&& p) : ptr(p.ptr) {p.ptr = 0;}
  MyClass& operator=(MyClass&& p) {
    std::swap(ptr, p.ptr);
    return *this;
  }
};

7.2.2 Generalized constant expressions

SWIG correctly parses the keyword constexpr, but ignores its functionality. Constant functions cannot be used as constants.

constexpr int myConstFunc() { return 10; }
const int a = myConstFunc(); // results in error

Users needs to use values or predefined constants when defining the new constant value:

#define MY_CONST 10
constexpr int myConstFunc() { return MY_CONST; }
const int a = MY_CONST; // ok

7.2.3 Extern template

SWIG correctly parses the keywords extern template. However, the explicit template instantiation is not used by SWIG, a %template is still required.

extern template class std::vector<MyClass>; // explicit instantiation

...

class MyClass {
public:
  int a;
  int b;
};

7.2.4 Initializer lists

Constructors using the std::initializer_list class are removed from the wrapped class, because the only way to access such a constructor is at compile time using the "= {}" assignment.

Users should add another constructor with specific arguments filling the class members manually.

For now, if a user wants to fill the class components like this:

class A {
public:
  A( std::initializer_list<int> );
};
A a1 = {1,2,3,4};

You should add another constructor using the std::vector for example:

class A {
public:
  A( std::initializer_list<int> );
  A( std::vector<int> );
};
A a1 = {1,2,3,4};

And call it from your target language, for example, in Python:

>>> a2 = A( [1,2,3,4] )

7.2.5 Uniform initialization

The curly brackets {} for member initialization are fully supported by SWIG:

struct BasicStruct {
 int x;
 double y;
};
 
struct AltStruct {
  AltStruct(int x, double y) : x_{x}, y_{y} {}
 
  int x_;
  double y_;
};

BasicStruct var1{5, 3.2}; // only fills the struct components
AltStruct var2{2, 4.3};   // calls the constructor

Uniform initialization does not affect usage from the target language, for example in Python:

>>> a = AltStruct(10, 142.15)
>>> a.x_
10
>>> a.y_
142.15

7.2.6 Type inference

SWIG supports decltype() with some limitations. Single variables are allowed, however, expressions are not supported yet. For example, the following code will work:

int i;
decltype(i) j;

However, using an expression inside the decltype results in syntax error:

int i; int j;
decltype(i+j) k;  // syntax error

7.2.7 Range-based for-loop

This feature is part of the implementation block only. SWIG ignores it.

7.2.8 Lambda functions and expressions

SWIG correctly parses most of the Lambda functions syntax. For example:

auto val = [] { return something; };
auto sum = [](int x, int y) { return x+y; };
auto sum = [](int x, int y) -> int { return x+y; };

The lambda functions are removed from the wrapper class for now, because of the lack of support for closures (scope of the lambda functions) in the target languages.

Lambda functions used to create variables can also be parsed, but due to limited support of auto when the type is deduced from the expression, the variables are simply ignored.

auto six = [](int x, int y) { return x+y; }(4, 2);

Better support should be available in a later release.

7.2.9 Alternate function syntax

SWIG fully supports the new definition of functions. For example:

struct SomeStruct {
  int FuncName(int x, int y);
};

can now be written as in C++0x:

struct SomeStruct {
  auto FuncName(int x, int y) -> int;
};
 
auto SomeStruct::FuncName(int x, int y) -> int {
  return x + y;
}

The usage in the target languages remains the same, for example in Python:

>>> a = SomeStruct()
>>> a.FuncName(10,5)
15

SWIG will also deal with type inference for the return type, as per the limitations described earlier. For example:

auto square(float a, float b) -> decltype(a);

7.2.10 Object construction improvement

SWIG is able to handle constructor delegation, such as:

class A {
public:
  int a;
  int b;
  int c;

  A() : A( 10 ) {}
  A(int aa) : A(aa, 20) {}
  A(int aa, int bb) : A(aa, bb, 30) {}
  A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; }
};

Constructor inheritance is parsed correctly, but the additional constructors are not currently added to the derived proxy class in the target language. Example is shown below:

class BaseClass {
public:
  BaseClass(int iValue);
};

class DerivedClass: public BaseClass {
  public:
  using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
};

7.2.11 Null pointer constant

The nullptr constant is largely unimportant in wrappers. In the few places it has an effect, it is treated like NULL.

7.2.12 Strongly typed enumerations

SWIG parses the new enum class syntax and forward declarator for the enums:

enum class MyEnum : unsigned int;

The strongly typed enumerations are treated the same as the ordinary and anonymous enums. This is because SWIG doesn't support nested classes. This is usually not a problem, however, there may be some name clashes. For example, the following code:

class Color {
  enum class PrintingColors : unsigned int {
    Cyan, Magenta, Yellow, Black
  };
  
  enum class BasicColors {
    Red, Green, Blue
  };
  
  enum class AllColors {
    // produces warnings because of duplicate names
    Yellow, Orange, Red, Magenta, Blue, Cyan, Green, Pink, Black, White
  };
};

A workaround is to write these as a series of separated classes containing anonymous enums:

class PrintingColors {
  enum : unsigned int {
    Cyan, Magenta, Yellow, Black
  };
};

class BasicColors {
  enum : unsigned int {
    Red, Green, Blue
  };
};

class AllColors {
  enum : unsigned int {
    Yellow, Orange, Red, Magenta, Blue, Cyan, Green, Pink, Black, White
  };
};

7.2.13 Double angle brackets

SWIG correctly parses the symbols >> as closing the template block, if found inside it at the top level, or as the right shift operator >> otherwise.

std::vector<std::vector<int>> myIntTable;

7.2.14 Explicit conversion operators

SWIG correctly parses the keyword explicit both for operators and constructors. For example:

class U {
public:
        int u;
};

class V {
public:
        int v;
};

class TestClass {
public:
        //implicit converting constructor
        TestClass( U const &val ) { t=val.u; }
        // explicit constructor
        explicit TestClass( V const &val ) { t=val.v; }

        int t;
};

The usage of explicit constructors and operators is somehow specific to C++ when assigning the value of one object to another one of different type or translating one type to another. It requires both operator and function overloading features, which are not supported by the majority of SWIG target languages. Also the constructors and operators are not particulary useful in any SWIG target languages, because all use their own facilities (eg. classes Cloneable and Comparable in Java) to achieve particular copy and compare behaviours.

7.2.15 Alias templates

The following is an example of an alias template:

template< typename T1, typename T2, int >
class SomeType {
  T1 a;
  T2 b;
  int c;
};

template< typename T2 >
using TypedefName = SomeType<char*, T2, 5>;

These are partially supported as SWIG will parse these and identify them, however, they are ignored as they are not added to the type system. A warning such as the following is issued:

example.i:13: Warning 342: The 'using' keyword in template aliasing is not fully supported yet.

Similarly for non-template type aliasing:

using PFD = void (*)(double); // New introduced syntax

A warning will be issued:

example.i:17: Warning 341: The 'using' keyword in type aliasing is not fully supported yet.

The equivalent old style typedefs can be used as a workaround:

typedef void (*PFD)(double);  // The old style

7.2.16 Unrestricted unions

SWIG fully supports any type inside a union even if it does not define a trivial constructor. For example, the wrapper for the following code correctly provides access to all members in the union:

struct point {
  point() {}
  point(int x, int y) : x_(x), y_(y) {}
  int x_, y_;
};

#include  // For placement 'new' in the constructor below
union P {
  int z;
  double w;
  point p; // Illegal in C++03; legal in C++11.
  // Due to the point member, a constructor definition is required.
  P() {
    new(&p) point();
  }
} p1;

7.2.17 Variadic templates

SWIG fully supports the variadic templates syntax (inside the <> block, variadic class inheritance and variadic constructor and initializers) with some limitations. The following code is correctly parsed:

template <typename... BaseClasses> class ClassName : public BaseClasses... {
public:
   ClassName (BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {}
}

Support for the variadic sizeof() function was also introduced:

const int SIZE = sizeof...(ClassName<int, int>);

For now however, the %template directive only accepts at most the number of arguments defined in the original template<> block:

%template(MyVariant1) ClassName<>         // ok
%template(MyVariant2) ClassName<int>      // ok
%template(MyVariant3) ClassName<int, int> // too many arguments

7.2.18 New string literals

SWIG fully supports unicode string constants and raw string literals.

// New string literals
wstring         aa =  L"Wide string";
const char     *bb = u8"UTF-8 string";
const char16_t *cc =  u"UTF-16 string";
const char32_t *dd =  U"UTF-32 string";

// Raw string literals
const char      *xx =        ")I'm an \"ascii\" \\ string.";
const char      *ee =   R"XXX()I'm an "ascii" \ string.)XXX"; // same as xx
wstring          ff =  LR"XXX(I'm a "raw wide" \ string.)XXX";
const char      *gg = u8R"XXX(I'm a "raw UTF-8" \ string.)XXX";
const char16_t  *hh =  uR"XXX(I'm a "raw UTF-16" \ string.)XXX";
const char32_t  *ii =  UR"XXX(I'm a "raw UTF-32" \ string.)XXX";

Note: SWIG currently incorrectly parses the odd number of double quotes inside the string due to SWIG's C++ preprocessor.

7.2.19 User-defined literals

SWIG parses the declaration of user-defined literals, that is, the operator "" _mysuffix() function syntax.

Some examples are the raw literal:

OutputType operator "" _myRawLiteral(const char * value);

numeric cooked literals:

OutputType operator "" _mySuffixIntegral(unsigned long long);
OutputType operator "" _mySuffixFloat(long double);

and cooked string literals:

OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars);
OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars);
OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);

Note that the %rename directive currently does not parse the double quotes, so these can't be easily accessed from target languages.

Use of user-defined literals such as the following still give a syntax error:

OutputType var1 = "1234"_suffix;
OutputType var2 = 1234_suffix;
OutputType var3 = 3.1416_suffix;

7.2.20 Thread-local storage

SWIG correctly parses the thread_local keyword. For example, a variable reachable by the current thread can be defined as:

struct A {
   thread_local int val;
};

The new C++0x threading libraries are ignored because each SWIG target language offers its own threading facilities.

7.2.21 Defaulting/deleting of standard functions on C++ objects

SWIG correctly parses the = delete and = default keywords. For example:

struct NonCopyable {
  NonCopyable& operator=(const NonCopyable&) = delete; /* Removes operator= */
  NonCopyable(const NonCopyable&) = delete;            /* Removed copy constructor */
  NonCopyable() = default;                             /* Explicitly allows the empty constructor */
  void *operator new(std::size_t) = delete;            /* Removes new NonCopyable */
};

This feature is specific to C++ only. The defaulting/deleting is currently ignored, because SWIG automatically produces wrappers for special constructors and operators specific to the target language.

7.2.22 Type long long int

SWIG correctly parses and uses the new long long type already introduced in C99 some time ago.

7.2.23 Static assertions

SWIG correctly parses and calls the new static_assert function.

template <typename T>
struct Check {
  static_assert(sizeof(int) <= sizeof(T), "not big enough");
};

7.2.24 Allow sizeof to work on members of classes without an explicit object

SWIG correctly calls the sizeof() on types as well as on the objects. For example:

struct A {
  int member;
};

const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++0x

In Python:

>>> SIZE
8

7.3 Standard library changes

7.3.1 Threading facilities

SWIG does not currently wrap or use any of the new threading classes introduced (thread, mutex, locks, condition variables, task). The main reason is that SWIG target languages offer their own threading facilities that do not rely on C++.

7.3.2 Tuple types and hash tables

SWIG does not wrap the new tuple types and the unordered_ container classes yet. Variadic template support is working so it is possible to include the tuple header file; it is parsed without any problems.

7.3.3 Regular expressions

SWIG does not wrap the new C++0x regular expressions classes, because the SWIG target languages use their own facilities for this.

7.3.4 General-purpose smart pointers

SWIG provides special smart pointer handling for std::tr1::shared_ptr in the same way it has support for boost::shared_ptr. There is no special smart pointer handling available for std::weak_ptr and std::unique_ptr.

7.3.5 Extensible random number facility

This feature extends and standardizes the standard library only and does not effect the C++ language and SWIG.

7.3.6 Wrapper reference

The new ref and cref classes are used to instantiate a parameter as a reference of a template function. For example:

void f( int &r )  { r++; }
 
// Template function.
template< class F, class P > void g( F f, P t )  { f(t); }
 
int main() {
  int i = 0 ;
  g( f, i ) ;  // 'g<void ( int &r ), int>' is instantiated
               // then 'i' will not be modified.
  cout << i << endl ;  // Output -> 0
 
  g( f, ref(i) ) ;  // 'g<void(int &r),reference_wrapper<int>>' is instantiated
                    // then 'i' will be modified.
  cout << i << endl ;  // Output -> 1
}

The ref and cref classes are not wrapped by SWIG because the SWIG target languages do not support referencing.

7.3.7 Polymorphous wrappers for function objects

SWIG fully supports function template wrappers and function objects:

function<int ( int, int )> pF;   // function template wrapper

struct Test {
  bool operator()( short x, short y ); // function object
};

7.3.8 Type traits for metaprogramming

The new C++ metaprogramming is useful at compile time and is aimed specifically for C++ development:

// First way of operating.
template< bool B > struct algorithm {
  template< class T1, class T2 > int do_it( T1&, T2& )  { /*...*/ }
};
// Second way of operating.
template<> struct algorithm<true> {
  template< class T1, class T2 > int do_it( T1, T2 )  { /*...*/ }
};
// Instantiating 'elaborate' will automatically instantiate the correct way to operate.
template< class T1, class T2 > int elaborate( T1 A, T2 B ) {
  // Use the second way only if 'T1' is an integer and if 'T2' is
  // in floating point, otherwise use the first way.
  return algorithm< is_integral<T1>::value && is_floating_point<T2>::value >::do_it( A, B );
}

SWIG correctly parses the template specialization, template types and values inside the <> block and the new helper functions: is_convertible, is_integral, is_const etc. However, SWIG still explicitly requires concrete types when using the %template directive, so the C++ metaprogramming features are not really of interest at runtime in the target languages.

7.3.9 Uniform method for computing return type of function objects

SWIG does not wrap the new result_of class introduced in the <functional> header and map the result_of::type to the concrete type yet. For example:

%inline %{
#include <functional>
double square(double x) {
        return (x * x);
}

template<class Fun, class Arg>
typename std::result_of<Fun(Arg)>::type test_result_impl(Fun fun, Arg arg) {
        return fun(arg);
}
%}

%template(test_result) test_result_impl<double(*)(double), double>;
%constant double (*SQUARE)(double) = square;

will result in:

>>> test_result_impl(SQUARE, 5.0)
<SWIG Object of type 'std::result_of< Fun(Arg) >::type *' at 0x7faf99ed8a50>

Instead, please use decltype() where possible for now.