簡體   English   中英

C ++ std :: function如何綁定到模板函數?

[英]how c++ std::function bind to a template function?

是否有任何可用於實現代碼的機制如下:

// T can be any type
std::function<T(int,int)> tf;

tf = [](int x, int y) -> int{
    return x + y;
};

cout << tf(4, 5) << endl;

tf = [](int x, int y) -> string{
    return "hello world";
}
cout << tf(4,5) << endl;

為了解決這個問題,我們需要T來:

  • 能夠進行類型擦除並保存任意類型的實例;
  • 可從這樣的實例轉換;
  • 重載<<操作符,並將其動態轉發到類型擦除的實例。

根據您可能的類型列表是否有界,我們可以將大部分繁重的工作推遲到boost::variantboost::any (在C ++ 17和更高std::variant分別為std::variantstd::any )。

variant版本很簡單:

template <class... Ts>
struct StreamableVariant : boost::variant<Ts...> {
    using boost::variant<Ts...>::variant;

    friend decltype(auto) operator << (std::ostream &os, StreamableVariant const &sv) {
        return boost::apply_visitor([&](auto const &o) -> decltype(auto) {
            return os << o;
        }, sv);
    }
};

// Usage
std::function<StreamableVariant<int, std::string>(int,int)> tf;

any版本都涉及更多的內容,因為我們需要手動鍵入-擦除流功能,而在構造時我們仍然知道對象的類型:

struct StreamableAny : boost::any {
    template <class T>
    StreamableAny(T &&t)
    : boost::any{std::forward<T>(t)}
    , _printMe{[](std::ostream &os, StreamableAny const &self) -> decltype(auto) {
        return os << boost::any_cast<T const &>(self);
    }}{ }

private:
    friend std::ostream &operator << (std::ostream &os, StreamableAny const &sa) {
        return sa._printMe(os, sa);
    }

    std::ostream &(*_printMe)(std::ostream &os, StreamableAny const &);
};

// Usage
std::function<StreamableAny(int,int)> tf;

除非前者可以隱式轉換為后者,否則您不能為可調用對象分配一個與std::function最初使用的返回類型不同的返回類型。 分配運算符將不是候選人

在另一種情況下,返回類型可以不同,即std::function對象的返回類型為void

std::function<void(int)> f = [](int) -> int { return 0; }

暫無
暫無

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

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