簡體   English   中英

std :: is_same用於void函數(...)和void類型?

[英]std::is_same for void function(…) and void type?

我得到了這段代碼:

template <class FunctionType> class Entry {
    std::function<FunctionType> internalFunction;

    template<class... Arguments>
    auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...)){

        if (std::is_same<decltype(internalFunction(arguments...)), void>::value) {
            internalFunction(arguments...);
        } else {
            auto result = internalFunction(arguments...);

            return result;      
        }
    }
};

Entry類是std::function包裝器。 它適用於所有返回類型,但有一個例外 - void 我無法讓它發揮作用。 我也試過std::is_void ,它對於void(...)類型的函數不返回true。 對於std::is_same

如何解決這個問題?

return internalFunction(arguments...);

即使internalFunction返回void

嘗試將結果存儲在中間對象中不起作用,因為您無法創建void類型的對象,因為它不是對象類型。

你的if不起作用,因為if是運行時條件,編譯器仍然需要編譯條件的兩個分支,因此它們必須都是有效的C ++。

如果需要創建中間結果類型的變量,則不能將該代碼用於void case。 您可以為返回void函數編寫部分特化:

template <class FunctionType> class Entry {
    std::function<FunctionType> internalFunction;

    template<class... Arguments>
    auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...))
    {

        auto result = internalFunction(arguments...);

        return result;      
    }
};

template <class... ArgTypes> class Entry<void(ArgTypes...)> {
    std::function<void(ArgTypes...)> internalFunction;

    template<class... Arguments>
    void operator()(Arguments... arguments) {
        internalFunction(arguments...);
    }
}; 

這將不會返回職能的工作void ,但不返回仿函數void ,這樣做是有點困難。

它遵循另一種解決方案,即基於sfinae而非部分專業化的解決方案。
我試圖提供一個最小的,完整的例子。
我也在這個例子中介紹了完美的轉發 ,但它與問題中的那個完全不同,所以我決定讓它更類似於那個。

#include<functional>
#include<type_traits>


template <class FunctionType> class Entry {
    std::function<FunctionType> internalFunction;

    template<typename R, typename... Args>
    typename std::enable_if<std::is_void<R>::value>::type
    invoke(Args... args) {
        internalFunction(args...);
    }

    template<typename R, typename... Args>
    typename std::enable_if<not std::is_void<R>::value, R>::type
    invoke(Args... args) {
        return internalFunction(args...);
    }

public:
    Entry(std::function<FunctionType> f)
        : internalFunction{f} { }

    template<class... Arguments>
    auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...)){
        return invoke<typename std::function<FunctionType>::result_type>(arguments...);
    }
};


int f() { return 42; }
void g() { }


int main() {
    Entry<int()> e1(&f);
    e1();
    Entry<void()> e2(&g);
    e2();
}

有關sfinae的更多詳細信息,請參見此處

暫無
暫無

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

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