如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )
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);
}
假设我想为一个特定的类型T
扩展返回的Wrapper
,并为该类型专门化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">
我可以通过为Foo
创建Wrapper
的显式专业化来绕过使用ReturnType
。然而,当我只想添加一些新功能(如ExtendedWrapper
)时,这需要复制Wrapper
中的所有代码(在我的实际生活中,这是一个实质性的类)。那么,这能做到吗?上面的方法有什么问题?
编译器已经告诉你问题是什么:
注意:忽略了候选模板:无法推断模板参数"t">
您需要显式指定模板参数。
template <>
typename ReturnType<Foo>::type build_wrapped<Foo>()
{ // ^~~~~
Foo t{};
return typename ReturnType<Foo>::type(t);
}
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- C++模板错误:"invalid explicitly-specified argument for template parameter"
- 为什么编译器说"candidate template ignored: couldn't infer template argument 'InputIterator'"?
- "Cannot convert Python object argument to type '<typename>'" - 使用 Cython 包装 C++ 类时出错
- 实现多类型算术运算符时如何解决"template argument deduction/substitution failure"
- C++线程"Call to non-static member function without an object argument"
- 尝试在类中编译内核,出现错误"__init__() got an unexpected keyword argument 'kernel'"
- 如何修复 eigen3 中的'non-type template argument is not a constant expression'?
- 密钥错误: "Couldn't find enum caffe.EmitConstraint.EmitType"
- LLVM:如何修复"Referring to an argument in another function"
- 如何修复此"argument of type incompatible with parameter"错误?
- Constexpr lambda argument
- 通过"Value Template Argument"与常规阵列在堆栈中分配内存
- 当我使用套接字代码发送第二条消息时,我有一个"sendto() Invalid argument"
- std::get from teplate argument
- 列表插入"Cannot convert argument from Class<T>* to Class<T> &&"
- 模板类错误的向量:"Template argument 2 is invalid"
- 如何修复错误消息,如"argument list for class template is missing"?
- 矩阵类:"No instance of overloaded function push_back matches the argument list"
- 如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )