Ashd Uiyuiy
Ashd Uiyuiy

Reputation: 29

compare instances of a template type and a concrete type

I guess sometimes while writing a template function you might have also run into cases which you need to compare the template parameter typed instance with a concrete typed instance like this

template<class A> void foo()
{
   A* something=new A(); //new A() mightnot exist
   if(*something==70000)
   {
      cout<<"Item 42\n";
   }
}

But it's important that template can't be leave out of your current design. How will you change and refactor your function ? I'm thankful you will share your experience in real life applications

Upvotes: 2

Views: 767

Answers (1)

Jason
Jason

Reputation: 32490

In any scenario that may arise like this, as long as your A class has the operator==() method defined for it, and it's implicitly convertible to the concrete type being compared to (i.e., no explicit casts are required), then there are no issues. Otherwise, you'll end up with a compiler error, which is a good thing, as it points out your mistakes at compile-time rather than at run-time.

For instance, imagine your A class is defined as follows:

template<typename T>
class A
{
private:
    T b;

public:
    A(): b(0) {}
    const T& value() const { return b; }

    template<typename U>
    bool operator==(const U& compare) { return compare.value() == b; }
};

Then as long as:

  1. The comparison U object type has a method called value() that can be called to fetch it's internal private "value"
  2. Whatever type U::value() returns is comparable (and implicitly convertable) to your template T type

you're fine. Otherwise you'll get a compiler error complaining about one of those two points.

Upvotes: 1

Related Questions