簡體   English   中英

有沒有辦法重載operator =以使右側的函數具有特定的行為

[英]Is there a way to overload operator= to have specific behavior for a function on right hand side

我有一個名為Image的類,我希望非成員函數返回到Image

Image::Image(const char * src);
Image::Image& operator= (const Image& p);
Image requestImg(std::string filename); //not a member function

我這樣使用它:

Image p = requestImg("grass.png");

這很好,但是我希望能夠讓requestImg生成一個線程,該線程將圖像加載到Image對象(p)中,同時修改該對象的狀態為loading=true

換一種說法。

Image p = requestImg("grass.png");  //image is loading
std::cout << p.loading << std::endl; //true
//some time passes
std::cout << p.loading << std::endl; //false

p最初不能將loading設置為true,因為它不會加載並且不會導致合理的命名。 我意識到使用成員函數這將更容易 - 甚至傳遞指向函數的指針,但有沒有辦法按照我的布局做到這一點?

您可以按原樣保留Image ,並使用std::async ,這將為您提供std::future<Image> 您可以決定何時需要結果:

#include <future>

auto p = std::async(std::launch::async, &requestImg,"grass.png"); // load image asynchronously
//some time passes
// do other work

// now we really need the image
auto img = p.get(); // blocking call, requires async call to be done loading image.

這是我用來實現這一目標的一般代碼(我很接近,但我們可以稱之為解決)。 它使用臨時futureImage來處理未來,並且復制構造函數重載以創建新線程並在將來填充this ... 這是類型:

class Image {
private:
        std::future<Image> * futureImage; //just a temporary for threading
        void threadingwork(); //this takes futureimage and sets values of self once it finishes
    public:
        Image(std::future<Image> p); //this sets loading = true, and sets the future + creates a thread which calls threadingwork above
};

std::future<Image> requestImg(std::string filename);

所以現在:

Image p = requestImg("grass.png"); 

正確解析(並正確使用復制構造函數)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM