I am watching the talk Modern Template Metaprogramming by Walter E. Brown. At 54:40 a code is given as below
template<class T, T v>
struct integral_constant{
static constexpr T value = v;
constexpr operator T() const noexcept { return value; } // what does this mean?
constexpr T operator T() const noexcept { return value; }
};
My question is what does this line mean
constexpr operator T() const noexcept { return value; }
, why there is no return type but it is still returning value
? Is this a typo?
Yes, the second operator line is wrong and can be deleted completely.
A type operator like eg. operator int()
is executed
when the object is casted or implicitly converted to the type:
MyClass myObject;
int i = myObject; // here operator int() is used.
Naturally, operator int()
has to return int
. It´s not necessary or allowed to write a specific return type for such operators. In your case, it´s not int
of float
or anything specific, but the template type, but it´s the same idea.
Aside from the return type problem, the second operator line defines the same operator with same parameters again, there can´t be multiple functions with same name and parameters.
And after the whole struct
, a semicolon is missing.
After fixing these problems, it compiles: http://ideone.com/Hvrex5
The first one is not a typo. That syntax is used to provide conversion from an object of the class to another type.
The return type is T
See http://en.cppreference.com/w/cpp/language/cast_operator for more info.
The consexpr
qualifier indicates to the compiler that return value of the member function can be determined at compile time if the object on which it is invoked is also constexpr
qualified.
The second one is not a legal statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With