Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 300
Allanqunzi Avatar asked Sep 03 '15 02:09

Allanqunzi


2 Answers

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

like image 81
deviantfan Avatar answered Nov 13 '22 10:11

deviantfan


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.

like image 3
R Sahu Avatar answered Nov 13 '22 12:11

R Sahu