专门化模板功能返回向量
假设我在文件上有一个读者类:
class Reader {
public:
template <class T>
T Read();
};
它的唯一函数是读取
函数,读取任何算术类型(static_assert(std :: is_arithmetic_v&lt; t&gt; t&gt;)
)文件。现在,我想创建该功能的专业化,该功能从文件中读取向量。我将如何使用模板进行操作?像以下内容不起作用:
template <class T>
std::vector<T> Read<std::vector<T>>();
error: function template partial specialization is not allowed
std::vector<U> Read<std::vector<U>>();
^ ~~~~~~~~~~~~~~~~
Let's say I have a reader class over a file:
class Reader {
public:
template <class T>
T Read();
};
Its only function is the Read
function that reads any arithmetic type (static_assert(std::is_arithmetic_v<T>)
) from a file. Now I want to create a specialization of that function, which reads a vector from the file. How would I go about doing that with templates? Something like the following doesn't work:
template <class T>
std::vector<T> Read<std::vector<T>>();
error: function template partial specialization is not allowed
std::vector<U> Read<std::vector<U>>();
^ ~~~~~~~~~~~~~~~~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能部分地专业化功能。不过,您可以超载它们,但是这样做的方式并不明显,因为您的功能没有任何参数。
首先,您需要一种方法来检查一种类型是否为
std :: vector&lt; ??&gt;
:然后,您可以将其插入
需要
:另外,您可以拥有一个单个功能,具有
,如果constexpr(ISVector&lt; t&gt; :: value)
内部。You can't partially specialize functions. You can overload them though, but the way of doing it is not obvious, since your function doesn't take any parameters.
First, you need a way to check if a type is a
std::vector<??>
:Then you can plug it into
requires
:Alternatively, you could have a single function, with
if constexpr (IsVector<T>::value)
inside.实施您想要的方法是将成员函数的逻辑委托给几个私人成员函数:
这不需要您引入新的类型特征以检查您的类型是否为
std :: vector&lt; &gt;
。但是,它要求您的返回类型默认可构建。输出:
A way to implement what you want is to delegate the logic of your member function to a couple of private member functions:
This doesn't require you to introduce new type traits to check if your type is a
std::vector<>
. However, it requires your return types to be default constructible.Output: