[linux-audio-dev] C++ wrapper for libsndfile

Lars Luthman lars.luthman at gmail.com
Sat Jul 29 13:29:26 UTC 2006


On Sat, 2006-07-29 at 23:14 +1000, Erik de Castro Lopo wrote:
> Lars Luthman wrote:
> 
> > The 4 different overloaded versions of the read, readf, write, and
> > writef functions will cause ambiguities that will force you to cast them
> > to their respective types in order to use pointers to them, for example
> > in functors (e.g. a sigc++ slot), like this:
> > 
> >   mem_fun(sndobj, (sf_count_t (Sndfile::*)(float*,
> > sf_count_t))&Sndfile::read);
> > 
> > If they were specialisations of the same template functions instead,
> > with the sample type as template parameter, you'd only have to write
> > this:
> > 
> >   mem_fun(sndobj, &Sndfile::read<float>);
> > 
> > which is a lot nicer and easier to read.
> 
> Interesting use case.
> 
> I'm not even close to being an expert in C++ templates, but
> I suppose that read function would then be defined as something
> like:
> 
>     template <T> sf_count_t read (T *ptr, sf_count_t items) ;
> 
> SO how do I ensure that <T> only gets specialised as short,
> int, float and double?

class Sndfile {
 ...
 template <typename T> sf_count_t read (T *ptr, sf_count_t items);
 ...
};

template <> sf_count_t Sndfile::read<short>(short* ptr, sf_count_t
items) { ... }
template <> sf_count_t Sndfile::read<int>(int* ptr, sf_count_t items)
{ ... }
template <> sf_count_t Sndfile::read<float>(float* ptr, sf_count_t
items) { ... }
template <> sf_count_t Sndfile::read<double>(double* ptr, sf_count_t
items) { ... }

...and nothing more. If you don't have a generic implementation anyone
who tries to instantiate the template with an unsupported type will get
a compilation error.

I don't think there is a way to actually prevent someone else from
writing a generic implementation or a different specialisation in their
own source, but if they try that they should _really_ know what they are
doing.

-- 
Lars Luthman - please encrypt any email sent to me if possible
PGP key: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x04C77E2E
Fingerprint: FCA7 C790 19B9 322D EB7A E1B3 4371 4650 04C7 7E2E
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
URL: <http://lists.linuxaudio.org/pipermail/linux-audio-dev/attachments/20060729/20949c8c/attachment.pgp>


More information about the Linux-audio-dev mailing list