return a value without return type declaration in template, is this a typo?
Asked Answered
P

2

6

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?

Pronty answered 3/9, 2015 at 2:30 Comment(3)
It's a conversion function. en.cppreference.com/w/cpp/language/cast_operatorConverge
The second line is actually constexpr T operator ()() const noexcept { return value; }, which is a function call operator.Photocomposition
Yes, you are right. I overlooked the slide.Pronty
R
9

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

Retain answered 3/9, 2015 at 2:46 Comment(5)
sorry, the semicolon for struct is fixed.Pronty
The second line in the talk is correct. The OP transcribed it wrong. And it's called a "conversion function", not a "type operator".Photocomposition
I watched it now, yes. OP: With the correct line, you can keep both operators, the first being the type op like explained here and the second is a normal op with return type like usual.Retain
@Photocomposition And it's called... How about "user-defined type-cast-or-implicit-conversion operator class method (member function)"? Really now...Retain
[class.conv.fct]/p1. That's what the standard calls it.Photocomposition
P
3

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.

Professor answered 3/9, 2015 at 2:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.