Re: std::complex and extensible literals.
On Apr 10, 2:11 pm, Carl Barron <cbarron...@adelphia.net> wrote:
In article
<6695dd7e-2ec0-4184-996b-2e206c387...@u12g2000prd.googlegroups.com>,
german diago <germandi...@gmail.com> wrote:
\> int main()
{
complex<double> c1 = 2.3 + 3i;
complex<double> c2 = 2.2 + 2i;
}
A natural way to define complex literals, don't you think so?
Yes. In fact, improving C++'s representation of complex number values
appears to have been one of the original, motivating factors behind
the extensible types proposal.
But why bog down the library with just syntactic sugar??
Because user-defined literal types in C++ are not some kind of
"syntactic sugar" that repackages an existing C++ language feature and
presents it as a new capability. On the contrary, the ability for a C+
+ programmer to define their own literal types - beyond the literal
types defined in the C++ Standard - is an entirely new, very powerful
and tremendously useful capability.
typedef std::complex<double> complex;
complex c1;
complex c2;
{
complex i(0,1);
c1 = 2.3 + 3*i;
c2 = 2.2 + 2*i;
}
does the trick and i goes out of scope after the initializations as
well, if i is used elsewhere in the same scope as c1,c2.
When compared to the user-defined literal in the original example, the
code above has many shortcomings: For one, "i" is the name of a
variable - not the name of a type. So whether the "i" in this case is
supposed to convey a particular type for the value being represented
- or whether any such connection is purely accidental - cannot always
be known for certain. Moreover, the expression "2*i" requires that an
operator*() be implemented, whereas the "2i" literal calls no
multiplication operator - only a constructor. Note also that the
runtime costs of the "2i" literal are lower - the literal type incurs
none of the runtime overhead required for "i"'s dynamic allocation,
initialization and destruction.
So for reasons of efficiency, ease of implementation, type safety and
overall expressive power, user defined literals are unquestionably a
great addition to the C++ language.
For more information about user defined literals, see:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2378.pdf
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]