gpt4 book ai didi

c++ - 来自模板特化的模板

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:28 25 4
gpt4 key购买 nike

有没有办法从模板特化中获取模板?例如。 std::unordered_map来自 std::unordered_map<char, char> 类型的变量作为模板模板参数传递。

最小的例子:

#include <unordered_map>

template <template <class ...> class t_map>
class A
{
public:
typedef t_map <int, int> map_type;
};

int main(int argc, char const **argv)
{
std::unordered_map<char, char> map;

// decltype yields std::unordered_map<char, char> (as expected).
typename A<decltype(map)>::map_type map_2;
return 0;
}

最佳答案

这是一个如何创建新类型的示例,其中模板参数 (int) 被交换(通过字符串):

#include <vector>
#include <string>

template <typename container, typename newt>
struct replace;

template <typename p1, typename alloc, template<typename,typename > class containerTemplate, typename newt>
struct replace<containerTemplate<p1,alloc>,newt> {
public:
typedef containerTemplate<newt,alloc> result;
};

int main() {
replace<std::vector<int>,std::string>::result vs;
vs.push_back("a string");
}

通过这种方式,您可以将 std::unordered_map 作为模板参数传递给您的函数,并将 char 替换为您想要的任何其他类型。您可能需要根据您的需要调整我的示例。但是原理应该很清楚。

编辑:容器更通用,替换更通用:

template <class Container>
struct replace;

template <template <class...> class Container, class... Ts>
struct replace<Container<Ts...>> {
typedef Container<std::string> result;
};

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com