簡體   English   中英

在這種情況下如何正確使用std :: enable_if

[英]how to use std::enable_if correctly in this case

我定義了以下方法:

template <typename Interface>
Interface Create();

通過此實現:

template <typename Interface>
typename std::enable_if<std::is_pointer<Interface>::value, Interface>::type Create()
{
...
}

但是現在出現以下錯誤:“對ITestInterface * Create()的未定義引用”

當我刪除std::enable_if ,一切正常。 但是我要求它能正常工作,因為我想添加該函數的版本,這些版本在Interface是引用或Interface是std::vector 我在這里做錯了什么? 我還注意到這是一個鏈接器錯誤-但我不知道為什么。 有人可以給我提示嗎?

在普通函數中, 返回類型不是簽名的一部分,而返回類型則是模板函數的簽名的一部分。
所以

template <typename Interface> Interface Create();

不同於

template <typename Interface>
typename std::enable_if<std::is_pointer<Interface>::value, Interface>::type
Create();

您必須在聲明和定義中使用相同的簽名。

由於無法對函數進行部分專業化,因此您必須使用helper類:可能會有所幫助:

namespace detail
{

template <typename > struct CreateHelper;

template <typename T> struct CreateHelper<T*>
{
    static T* create() {
        // Implementation with T*
    }
};

template <typename T> struct CreateHelper<T&>
{
    static T& create() {
        // Implementation with T&
    }
};

template <typename T> struct CreateHelper<std::vector<T>>
{
    static std::vector<T> create() {
        // Implementation with std::vector<T>
    }
};

} // namespace detail


template <typename Interface> Interface Create()
{
    return detail::CreateHelper<Interface>::create();
}

暫無
暫無

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

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