Ram
Ram

Reputation: 369

Compare a map object and its reference C++

I have the following maps

map<int,string> m1;
map<int,string> m2;
call(m1);
call(m2);

template<typename T>
void call(T &m)
{
  // Compare if m == m1
  How to do?
}

I need to know which of m1 and m2 is being called in the current function at run time.

Upvotes: 2

Views: 56

Answers (2)

Smeeheey
Smeeheey

Reputation: 10316

To improve on the accepted answer, if you want to avoid compiler errors due to the function call being called on types other than map<int, string>, you need a template helper function:

template <typename T, typename U>
bool is_equal(const T& t, const U& u)
{
    return false;
}

template <typename T>
bool is_equal(T& t, T& u)
{
    return &t == &u;
}

template<typename T>
void call(T &m)
{
  // Compare if m == m1
  if(is_equal(m, m1))
    std::cout << "Yes";
  else
    std::cout << "No";
}

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172894

If you want to check it based on the contents of map, you can use operator==:

template<typename T>
void call(T &m)
{
  if (m == m1)
    ...
}

If you want to identify whether they're the same instance, since the parameter is passed by reference, you can compare their addresses:

template<typename T>
void call(T &m)
{
  if (&m == &m1)
    ...
}

As @Smeeheey pointed, you need to consider about how to provide the compared object (i.e. m1 or its address) inside the template function, and it's not clear from your snippets.

Upvotes: 3

Related Questions