C++ 将部分专用模板作为模板参数传递
我有一个类模板,需要其他模板作为参数:C++ 将部分专用模板作为模板参数传递,c++,templates,metaprogramming,C++,Templates,Metaprogramming,我有一个类模板,需要其他模板作为参数: 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 K,template <typename T> class Allocator> class Policy
>
class container {
Policy<Key,Allocator>* _policy;
//some code here
};
模板<
类密钥,
模板类策略
>
类容器{
政策*\u政策;
//这里有一些代码
};
通常我在策略类中使用它,如下所示:
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
};
模板类策略\u 3{
//一些代码
};
我能做些什么,允许该类用户在不接触其他人的情况下通过年龄参数表?例如:
typedef container<key_type,policy_3<100500> > containerWithAge;
typedef集装箱及其包装;
您有两个选项:绑定和重新绑定
在绑定中,您将三元策略调整为二元策略,正如模板参数policy
所预期的那样:
template <typename Key, template <typename T> class Allocator>
struct policy_3_100500 : ternary_policy<100500,Key,Allocator> {};
并使用policy\u 3::type
而不是policy\u 3
获得所需语法的唯一方法是使用策略将::type
移动到类中。这是第二个选项:重新绑定(顺便说一句,这也用于std::allocator)。在本例中,您将策略
作为普通模板参数传递,并假设存在一个模板元函数,例如bind
:
template <time_t Age>
struct policy_3 {
template <typename Key, template <typename T> class Allocator>
struct bind : ternary_policy<Age,Key,Allocator> {};
};
一般来说,策略类通常不是作为模板参数传递的,而是作为普通模板参数传递的(正是因为它们本身可能有不同数量的参数)。然后,使用策略的类假设策略中存在某种内部结构(typedef、函数、元函数、常量),其中的
bind
只是一个示例。将模板更改为简单的模板
不是我假设的选项:PSo五年后,我遇到了与您完全相同的问题并找到了相同的解决方案,但我的代码仍然没有使用编译,需要一个类模板,得到了X::type
。问题是我将X::type
作为从属参数传递给另一个模板,因此正确的语法是X::template type
。如果gcc有更多有用的错误消息就好了。
template <time_t Age>
struct policy_3 {
template <typename Key, template <typename T> class Allocator>
struct bind : ternary_policy<Age,Key,Allocator> {};
};
template <typename Key, typename Policy>
struct container {
typename Policy::template bind<Key,std::allocator<Key>> * _policy;
// ...
}: