user3061876
user3061876

Reputation: 161

C++ constexpr overloads constructor with same name

I do understand the use of constexpr when using it on expressions that can be calculated before runtime.

I want to create a constexpr for complex numbers. x = 5_i should create an complex number of my own complex class I have created and to do it I need a constantexpr constructor.

class Complex {
private:
    double real_;
    double imag_;

public:
    ...
    Complex(double real, double imaginary);

    constexpr Complex(double real, double imaginary):
        real_(real),imag_(imaginary) {};

//Nonmember function
constexpr Complex operator""_i(long double arg);

The Complex(double real, double imaginary);is later defined in the .cpp file.
When I try to compile this, I get the following error :

‘constexpr Complex::Complex(double, double)’ cannot be overloaded with  
‘Complex::Complex(double, double)’

If I define just the constexpr function my conclusion is that I cannot use Complex::Complex(double, double) in runtime.

Why cannot I define two different functions? Is this not allowed in C++? Can the compiler not see the difference between the two functions? Is there any other way to do it?

Upvotes: 0

Views: 1188

Answers (2)

Jive Dadson
Jive Dadson

Reputation: 17026

I would not roll my own complex type. Leave the drudgery to the library writers, hunched over their keyboards like medieval monks copying manuscripts.

I do not know why the operator has to take long double rather than just double, but that's the law.

#include <complex>
using Complex = std::complex<double>;

constexpr Complex operator"" _i (long double val) {
    return Complex(0.0,  static_cast<double>(val));
}

Upvotes: 1

Mihayl
Mihayl

Reputation: 3911

Even if you define it constexpr you can still use it at run-time. You do not need two different overloads and you cannot overload only on constexpr.

The constexpr User-defined literals need constexpr constructor so that the compiler can create and initialize objects of the class at compile-time. The constexpr constructor places some restrictions on the constructor but allows constant initialization.

constexpr Complex a = 1.0_i;
const Complex b = 1.0_i;

If you look at the std::complex you'll see that it also have constexpr constructors.

Upvotes: 5

Related Questions