1

I'd like to define multiple ways of assignment operators. Minimal example code.

enum class AssignType {
    DeepCopy,
    SharedCopy
};

struct Container
{
    const char* x;
    template<AssignType >
    Container& operator=(const Container& other) {
        x = other.x; return *this;
    }
    // ...some specialisations of operator=() could be made
};

int main()
{
    Container i1, i2;
    i2.operator=<AssignType::DeepCopy>(i1);
    i2 =<AssignType::DeepCopy> i1; // line 20
    return 0;
}

The g++'s parser gives me an error for line 20. Is there any way to use operators in the "short" form (like in line 20) with explicit templates? C++11 allowed.

Johannes
  • 2,901
  • 5
  • 30
  • 50
  • `const char* x; x = other.x;` is not a deep copy. however, how do you decide when it is a deep/shallow copy? is Container able to hold both at the same time? – user1810087 Nov 11 '13 at 11:30
  • No, there's no way to do this with that notation. You can write non-operator/named function template..., but of course that won't support the `=` notation. You could easily use two wrapper classes instead of an enum to support a notation like `i2 = DeepCopy(i1)`. – Tony Delroy Nov 11 '13 at 11:30
  • @itwasntpete: that's kind of the point - there's a postulated shallow copy default, and implied deep copy specialisation. – Tony Delroy Nov 11 '13 at 11:32
  • Fixed. It should not have a name, anyways... – Johannes Nov 11 '13 at 11:50
  • 1
    all caps is conventionally reserved for macros. – Puppy Nov 11 '13 at 11:51
  • 1
    There are [Yakk](http://stackoverflow.com/users/1774667/yakk)'s named operators, e.g. `i2 = i1;` (probably `i2 = i1` works with the same trick), follow [this answer and the links in the comments](http://stackoverflow.com/a/15090751/420683) – dyp Nov 11 '13 at 12:13
  • It won't work with the same trick. – Puppy Nov 11 '13 at 12:23
  • @DeadMG m( Of course. I was too tired and read `<=` instead of `=<`. So `i2 <=DeepCopy> i1;` was possible, but ugly. – dyp Nov 11 '13 at 13:04

0 Answers0