gpt4 book ai didi

c++ - 将部分专用模板作为模板参数传递

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

我有一个类模板,需要一些其他模板作为参数:

template<
class Key,
template <typename K,template <typename T> class Allocator> class Policy
>
class container {
Policy<Key,Allocator>* _policy;
//some code here
};

通常我将它与这样的策略类一起使用:

template <class Key,template <typename T> class Allocator> class policy {
//some code
};

但是如果我必须将额外的模板参数传递给策略类怎么办?像这样的东西:

template <time_t Age,class Key,template <typename T> class Allocator> class policy_3 {
//some code
};

我该怎么做,才能让那个类(class)的用户在不接触其他人的情况下通过年龄参数表?例如:

typedef container<key_type,policy_3<100500> > containerWithAge;

最佳答案

您有两个选择:绑定(bind)和重新绑定(bind)。

在绑定(bind)中,您将三元策略调整为二进制策略,正如模板模板参数 Policy 所期望的那样:

template <typename Key, template <typename T> class Allocator>
struct policy_3_100500 : ternary_policy<100500,Key,Allocator> {};

并使用policy_3_100500而不是 policy_3<100500> .

为了更接近您所追求的语法,您可以使用嵌套类:

template <time_t Age>
struct policy_3 {
template <typename Key, template <typename T> class Allocator>
struct type : ternary_policy<Age,Key,Allocator> {};
};

并使用policy_3<100500>::type而不是 policy_3<100500> .

准确获得所需语法的唯一方法是移动 ::type 进入 使用策略的类(class)。这是第二个选项:重新绑定(bind)(顺便说一句,这也用在 std::allocator 中)。在这种情况下,您传递 Policy作为一个普通的模板参数,并假设一个模板元函数,比如说 bind , 存在:

template <time_t Age>
struct policy_3 {
template <typename Key, template <typename T> class Allocator>
struct bind : ternary_policy<Age,Key,Allocator> {};
};

虽然在结构上与第二个选项相同,但区别在于谁调用 bind :在第一个选项(绑定(bind))中,它是策略类的用户(通过显式传递 policy<100500>::type)。这里是使用策略的类:

template <typename Key, typename Policy>
struct container {
typename Policy::template bind<Key,std::allocator<Key>> * _policy;
// ...
}:

一般来说,Policy 类通常不作为模板参数传递,而是作为普通模板参数传递(正是因为它们本身可能有不同数量的参数)。使用该策略的类然后假设某个内部结构(typedef、函数、元函数、常量)出现在策略中,其中 bind只是一个例子。

关于c++ - 将部分专用模板作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5787006/

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