C++ templates constants and typedefs

  • You can’t easily typedef template classes (see C++11) so it’s not obvious how to give multiple names to equivalent classes. I wanted to do that so that a user can instantiate ws2812 or ws2812b or ws2812s or ws2801 etc. and get the same class. To fix that I just used a define.
  • You can use templates to map types, but also constants and functions!
template<class myType>
class foo {
  myType * _a;

template<int myConstant>
class foo {
  int * _a;
  foo() { _a = malloc(myConstant * sizeof(int));};

typedef int(*binary_int_op)(int, int); // signature for all valid template params
template<binary_int_op op>
int do_op(int a, int b) { return op(a,b); }

int add(int a, b) { return a + b; }
int c = do_op<add>(4,5);

I need to hardcode bitbanging timings into my ws2812b class for example, so I created a bitbanging template class, and have my ws2812b class inherit it, setting the constants. That’s clean!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s