mardi 5 avril 2016

Template branching with respect to a specific interface type

I'd like to distinguish when a template type implements a given interface. I thought I could achieve this by using a generic template method and its specialization for the interface type interested in. If I the method is call with a type that implements that specific interface, the compiler will resolve it with a call to the specialize method. Otherwise, it will call the generic method. For example, I summarize this idea in in the following code snippet :

#include <iostream>
#include <string>

struct Info {
  virtual std::string whoAmI() = 0;
};

struct Person: Info {
  std::string whoAmI() { return "Person"; }
};

template<typename T>
bool is_info(const T &)
{
  return false;
}

template<>
bool is_info(const Info& )
{
  return true;
}

int main()
{
  std::cout << is_info(1) << std::endl;
  std::cout << is_info(Person()) << std::endl;
}

Unfortunately, this code doesn't work. is_info(Person()) returns 0, when it should return 1. Why? How can I achieve what I need?

Aucun commentaire:

Enregistrer un commentaire