0

A simple class with explicit conversion constructor.

class MyDouble {
    double d;
public:
    MyDouble() : d(0) {}
    explicit MyDouble(double d_) : d(d_) {}
    MyDouble & operator =(double d_) {
        d = d_; return *this;
    }
};

I add an assignment on purpose to make it can be assigned constructed from double.

MyDouble a; 
a = 1.1;                    // this works
MyDouble b = MyDouble(1.1); // this works
MyDouble c(1.1);            // this works
MyDouble d = 1.1;           // this does not work 

I do not want implicit conversion, cause it will cause some other problems. But I still want direct assignment work, but it does not. Is there anyway to make the last statement MyDouble d = 1.1; work without deleting the explicit keyword.

phy nju
  • 289
  • 2
  • 7

1 Answers1

0

The answer to your question is 'no', there is no way to allow MyDouble d = 1.; without removing the explicit.

You could simply use MyDouble d(1.); or MyDouble d{1.}; instead of using assignment-initialization. That would allow you to retain the explicit while also being clear you are initializing.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
  • Nit-pick: it is [*copy initialization*](http://en.cppreference.com/w/cpp/language/copy_initialization), not *assignment-initialization*. – juanchopanza Jan 07 '18 at 07:40