【问题标题】:How to return a template container (i.e. vector, list, array) in a function?如何在函数中返回模板容器(即向量、列表、数组)?
【发布时间】:2019-11-13 01:41:51
【问题描述】:

我有以下课程:

class Conversion {
//...
public:
    template<class T,
        template<class, class = std::allocator<T>> class> T doTheWork()
    {
        //do the work
        return {};
    }
};

我想将内容复制到一个顺序容器(向量、列表、双端队列),声明为:

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();
}

【问题讨论】:

  • 您可以使用答案here 中使用的技巧,您可以使用模板化转换运算符返回代理类型

标签: c++ c++11 templates c++14 std


【解决方案1】:

如果要分别指定元素类型和容器类型,可以

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。它们只能从函数参数中推导出来。所以你必须明确指定它们。

如果可能,编译器将从函数参数中推断出缺少的模板参数。

如果不想写两次,可以申请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>>();

【讨论】:

  • 谢谢,但我在这里要避免的是调用方法conv.doTheWork&lt;std::vector&lt;std::string&gt;&gt;();时的类型显式@
  • 模板参数要么必须明确说明,要么必须推导出来。模板参数可以从函数参数中推导出来,并且从 C++17 开始,可以从构造函数参数中推导出来。最后,如果没有给出类型,您可以定义默认类型。但是如果要实例化该类,编译器需要知道 somewhere 的类型。
  • @anc 回答已修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 2022-07-18
  • 1970-01-01
  • 2021-03-23
  • 2020-07-22
  • 1970-01-01
相关资源
最近更新 更多