c++ - 模板中的模板。在模板函数中特化模板类

标签 c++ templates stl

在下面的示例中,我想使用模板函数 f 获取一个 STL 容器(list 或 unordered_set)。我知道 STL 容器将包含整数。

我尝试使用部分模板模板特化,但它不起作用。

我如何实现我想要的?

上面的代码显然不能编译。

#include <list>
#include <unordered_set>

template <typename T, template C<T>>
C<T> f()
{
    C<T> d;
    d.insert(1);
    return d;
}

int main()
{
    auto l = f<int, std::list<int>>();
    auto s = f<int, std::unordered_set>();

    return 0;
}

谢谢。

最佳答案

你至少会遇到问题 std::list不需要 insert同理std::unordered_set做。前者需要职位;后者没有。

除此之外,我可以让它编译和执行(不要忘记你需要实例化模板):

template <typename T, typename C>
C f()
{
    C d;
    d.insert(1);
    return d;
}

template std::unordered_set<int> f<int, std::unordered_set<int>>();

但是您将无法以这种方式使用列表。

这样的事情你能接受吗?如果不是,我认为您需要就您想要的内容进一步澄清您的问题。

关于c++ - 模板中的模板。在模板函数中特化模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38314980/

相关文章:

c++ - 在一行的末尾插入一个字符串

c++ - unordered_map 仅使用 16 个字符串来最大化唯一键

c++ - 基于模板参数的条件编译时类型映射

c++ - 如何将指针映射公开为 const 指针映射?

c++ - SFINAE检测静态方法

c++ - clang 与 gcc 和 msvc 中方法指针的模板

templates - Angular SubViews/多区域模板、指令和动态模板 URL

c++ - 在winsock中将 vector 重用为数组的更有效方法?

c++ - map可以包含类对象还是类对象?

c++ - 在 C++ 中重载 operator new 和 operator new[] 有什么区别?