繁体   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