[PyQt] Templated classes with specialization in SIP

Phil Thompson phil at riverbankcomputing.com
Tue Oct 5 18:28:43 BST 2010


On Tue, 5 Oct 2010 10:13:26 -0700, Nate Reid <gnatty7 at hotmail.com> wrote:
> There may be syntax/programming errors here, but I was wondering if by 
> specifying something like the following:
> 
> 
> 
> // blah.h
> 
> #ifndef BLAH_DEFINED
> 
> #define BLAH_DEFINED
> 
> #include <sstream>
> 
> template<typename T>
> 
> class Blah {
> 
> public:
> 
>    QString get(const T& v);
> 
> };
> 
> 
> 
> template<typename T>
> 
> QString Blah<T>::get(const T& v) {
> 
>    std::ostringstream s;
> 
>    s << "Value is: " << v;
> 
>    return QString(s.str().c_str());
> 
> }
> 
> 
> 
> // Specialization for 'int'
> 
> template<>
> 
> QString Blah<int>::get(const int& v) {
> 
>    std::ostringstream s;
> 
>    s << "Value (int) is: " << v;
> 
>    return QString(s.str().c_str());
> 
> }
> 
> #endif
> 
> 
> 
> // blah.sip
> 
> %Module blah 0
> 
> 
> 
> template <typename T>
> 
> class Blah {
> 
> %TypeHeaderCode
> 
> #include "blah.h"
> 
> %End
> 
> public:
> 
>    QString __getitem__(const T& val);
> 
> %MethodCode
> 
>    sipRes = new QString(sipCpp->get(*a0));
> 
> %End
> 
> };
> 
> 
> 
> 
> 
> You could produce a wrapped class that would work like follows:
> 
> 
> 
>>>> import blah
> 
>>>> b = blah.Blah()
> 
>>>> str(b['hello'])
> 
> Value is: hello
> 
>>>> str(b[3.2])
> 
> Value is: 3.2
> 
>>>> str(b[10])
> 
> Value (int) is: 10
> 
> 
> 
> It seems like without explicit typedefs, SIP won't know how to generate 
> the templated wrapped Blah.

Correct.

> But, is there a preferred way to get the 
> above interface with minimal code without necessarily resorting to using

> %MappedTypes?

Only if you know all the types in advance, in which case you can just
overload __getitem__().

Phil


More information about the PyQt mailing list