简体   繁体   中英

C++, template class as function's return type problem

static absl::StatusOr<ImageFrame> ReadTextureFromFile() {
      ImageFrame image_frame(width, height);
      return image_frame;
}

Why return type is ImageFrame, not absl::StatusOr ?

The return type is absl::StatusOr<ImageFrame> as specified in the signature of the function.

But looking at the definition of absl::StatusOr , there is a converting constructor that moves an object of type T into a absl::StatusOr<T> so your code is executed as if you wrote

static absl::StatusOr<ImageFrame> ReadTextureFromFile() {
      ImageFrame image_frame(width, height);

      // Call absl::StatusOr(U&&)
      absl::StatusOr<ImageFrame> returnValue{ image_frame };
      return returnValue;
}

This is just a "syntactic sugar". The return type is abseil::StatusOr<ImageFrame> . abseil::StatusOr<T> allows you to return both abseil::Status and the type T from your function. When there is an error you can directly return the error status. On success, you return the object with type T .

So you could also write something like that:

static absl::StatusOr<ImageFrame> ReadTextureFromFile() {
      try {
          ImageFrame image_frame(width, height);
      }
      catch{
          return absl::AbortedError("Could not create image frame.");
      }
      return image_frame;
}

When you call this function, you need to check if everything went smooth.

auto image_frame_or = ReadTextureFromField();
ImageFrame image_frame;
if (image_frame_or.ok()){
    image_frame = image_frame_or.value();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM