我有以下类(class):
class Conversion {
//...
public:
template<class T,
template<class, class = std::allocator<T>> class> T doTheWork()
{
//do the work
return {};
}
};
我想将内容复制到顺序容器(vector、list、deque),声明为:
template<class T, class Allocator = std::allocator<T>>
我对模板声明感到困惑。
考虑到我想像下面的例子一样接收接收者,我应该如何声明copyContentToContainer
?
例子:
int main() {
Conversion conv;
std::vector<std::string> container1 = conv.doTheWork();
std::list<int> container2 = conv.doTheWork();
std::deque<double> container3 = conv.doTheWork();
}
最佳答案
如果要分别指定元素类型和容器类型,可以
template<class T, template<class, class = std::allocator<T>> class C>
C<T> doTheWork()
{
//do the work
return {};
}
然后
std::vector<std::string> container1 = conv.doTheWork<std::string, std::vector>();
std::list<int> container2 = conv.doTheWork<int, std::list>();
std::deque<double> container3 = conv.doTheWork<double, std::deque>();
否则,你可以
template<class T>
T doTheWork()
{
//do the work
return {};
}
然后
std::vector<std::string> container1 = conv.doTheWork<std::vector<std::string>>();
std::list<int> container2 = conv.doTheWork<std::list<int>>();
std::deque<double> container3 = conv.doTheWork<std::deque<double>>();
顺便说一句:模板参数不能是deduced从返回类型。它们只能从函数参数中推导出来。所以你必须明确指定它们。
When possible, the compiler will deduce the missing template arguments from the function arguments.
如果你不想将它们写两次,你可以应用 auto
(C++11 起)。
auto container1 = conv.doTheWork<std::vector<std::string>>();
auto container2 = conv.doTheWork<std::list<int>>();
auto container3 = conv.doTheWork<std::deque<double>>();
关于c++ - 如何在函数中返回模板容器(即 vector 、列表、数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58829148/