簡體   English   中英

如何在返回類型功能模板的專業化中使用派生類型? (“無法推斷模板參數”)

[英]How to use derived type in specialisation of return-type function template? (“couldn't infer template argument”)

我有一個模板類和一個帶有模板返回類型的函數:

template<typename T>
class Wrapper {
public:
    Wrapper(const T& _data) : data(_data) { }

    const T& get_data() {return data;};
private:
    T data;
};

template <typename T>
Wrapper<T> build_wrapped(){
    T t{};
    return Wrapper<T>(t);
}

假設我想將返回的Wrapper擴展為一種特定的類型T並對該類型專門化build_wrapped()函數。 因此,讓我們創建一個模板來保存返回類型,並在build_wrapped()使用它:

template<typename T>
struct ReturnType {
    using type = Wrapper<T>;
};

template <typename T>
typename ReturnType<T>::type build_wrapped(){
    T t{};
    return typename ReturnType<T>::type(t);
}

並使用它來提供專業化:

struct Foo{};

class ExtendedWrapper : public Wrapper<Foo> {
public:
    ExtendedWrapper(const Foo& _data) : Wrapper(_data) {}
    int get_answer() {return 42;};
};

template<>
struct ReturnType<Foo> {
    using type = ExtendedWrapper;
};

template<>
typename ReturnType<Foo>::type build_wrapped(){
    Foo t{};
    return typename ReturnType<Foo>::type(t);
}

但是,最終聲明被gcc和clang拒絕。 例如, clang返回:

錯誤:沒有功能模板與功能模板專業化“ build_wrapped”匹配

注意:候選模板被忽略:無法推斷模板參數“ T”

我能得到周圍使用ReturnType通過創建一個明確的專業化WrapperFoo 但是,當我只想添加一些新功能時(如ExtendedWrapper ),這需要復制Wrapper所有代碼(在我的現實生活中,這是一個實質性的類)。 那么,這可以做到嗎? 上面的方法有什么問題?

編譯器已經告訴您問題所在:

注意:候選模板被忽略:無法推斷模板參數“ T”

您需要明確指定template參數。

template <>
typename ReturnType<Foo>::type build_wrapped<Foo>()
{ //                                        ^~~~~
    Foo t{};
    return typename ReturnType<Foo>::type(t);
}

暫無
暫無

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

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