views:

166

answers:

3

Are there exceptions for types which can't have thier assignment operator overloaded?

Specifically, I'm wanting to overload the assignment operator of a struct tm (from time.h) so I can assign a sql::ResultSet to it.

I already have the conversion logic:

sscanf(sqlresult->getString("StoredAt").c_str(), "%d-%d-%d %d:%d:%d",
  &TempTimeStruct->tm_year, &TempTimeStruct->tm_mon, &TempTimeStruct->tm_mday,
  &TempTimeStruct->tm_hour, &TempTimeStruct->tm_min, &TempTimeStruct->tm_sec);

I tried the overload with this:

tm& tm::operator=(sql::ResultSet & results)
{
  /*CODE*/
  return *this;
}

However VS08 reports:

error C2511: 'tm &tm::operator =(sql::ResultSet &)' : overloaded member function not found in 'tm'

+1  A: 

The assignment operator must be a member function (of struct tm in this case), so the only way of doing this would be to modify the standard library itself, something you should definitely not do. You can of course write a named free function to do whatever you want.

anon
Grand thanks, already done just thought i wuold try and score some extra assignment marks as its the only place im doing any kind of assignment.
Luke Mcneice
@Luke if this is for school, i strongly discourage you to introduce this "cleverness" into your code. I imagine most teachers will punish you for that.
Johannes Schaub - litb
@Johannes thanks for the heads up
Luke Mcneice
A: 
struct mytm : public tm {
  mytm& operator =(tm const& input) {
     /* whatever you want it to do. */
  return *this;
};

Some folks don't think much of this. I'll attach the following caveat:

If you got a ton of tm items (or any other classic c-lib struct) floating around in your code, and you want to take control over them, wrapping a class around them this way allows you do so. Just doing it for a 3-line knockoff is probably not a great idea. It's possible that the critics would prefer:

struct mytm {
  tm the_tm;
  /* etc */
};

Instead.

bmargulies
Bad for any number of reasons.
anon
Well, I've made good use of it over the years. Chacun a son goat.
bmargulies
I can see that this could be useful in some situations.
Luke Mcneice
A: 
tm to_tm(sql::ResultSet const& results) {
  tm ret;
  int r = sscanf(results->getString("StoredAt").c_str(), "%d-%d-%d %d:%d:%d",
    &ret->tm_year, &ret->tm_mon, &ret->tm_mday,
    &ret->tm_hour, &ret->tm_min, &ret->tm_sec);
  if (r != 6) throw std::runtime_error("sscanf: unexpected results");
  return ret;
}

void example() {
  tm t = to_tm(results);
}
Roger Pate
@Roger thanks for the error handling hints
Luke Mcneice