Question

I have the following code,

#include <iostream>
#include <tuple>

static inline void print (void)
{
  ;
}

template <typename Head, typename... Tail>
static inline void print (Head h, Tail... t)
{
  std::cout << h << std::endl;
  print(t...);
}

int main(int argc, char *argv[])
{

  print("string", 42, 3.43, true, 'c');

  return 0;
}

Is there a way to specialize for the first type, Head, with, for example, a bool? What I am looking is the proper syntax I would need to do this. I have tried adding this extra template,

template <bool, typename... Tail>
static inline void print (bool h, Tail... t)
{
  std::cout << "I'm a bool!" << std::endl;
  print(t...);
}

to no avail.

Was it helpful?

Solution

In C++ there is no such thing as a partial specialization of a function template.

That is true for C++03 and also for C++11, and is true for all function templates not only variadic ones.

You can overload the function though:

template <typename... Tail>
static inline void print (bool h, Tail... t)
{
  std::cout << "I'm a bool!" << std::endl;
  print(t...);
}

That overload will be used when the first argument is a bool.

OTHER TIPS

Function overload is enough, but you need to declare all the signature first, the code below works here, but if you remove the declaration of the bool overload like here, then it will not be picked.

#include <iostream>

void print (void){}
template <typename... Tail>
void print (bool b, Tail&&... t);
template <typename Head, typename... Tail>
void print (Head&& h, Tail&&... t);


template <typename Head, typename... Tail>
void print (Head&& h, Tail&&... t) {
  std::cout << std::forward<Heal>(h) << " ";
  print(std::forward<Tail>(t)...);
}

template <typename... Tail>
void print (bool , Tail&&... t) {
  std::cout <<"bool" << " ";
  print(std::forward<Tail>(t)...);
}

int main(int argc, char *argv[]) {
  print("string", 42, true, 3.43, true, 'c');
  return 0;
}

EDIT : Added universal reference for a real solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top