c++ - 如何在函数中返回模板容器(即 vector 、列表、数组)?

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

我有以下类(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/

相关文章:

c++ - 从指针删除到指针 vector

C++ 在变量中保存对象的引用

c++ - 在调试或 Release模式下使用 DLL?

c++ - CSV 文件中的 Unordered_map 值

php - 我需要一个可以与 PHP(服务器端)和 Javascript(客户端)一起使用的模板系统(基于 XML)

c++ - 模板函数 : perform conversion based on typename

c++ - volatile 是在 C/C++ 中生成单字节原子的正确方法吗?

c++ - 使用 std::bind 删除参数

c++ - 基于 unique_ptr 的 pimpl 类中的移动构造函数是否需要完整类型?

c++ - 相似数值类型的模板冲突