简体   繁体   English

如何专门化具有指向成员参数的指针的模板类?

[英]How to specialize a template class which has a pointer to member parameter?

Class definition is as follows: 类的定义如下:

template<typename T, list_node T::* node> class linked_list
{
    // ...
};

and can be instantiated like: 可以像这样实例化:

linked_list<foo, &foo::node> list;

But I would like a way to allow the user to instantiate as follows: 但是我想要一种允许用户实例化的方法,如下所示:

linked_list<foo> list2;

and have a specialization of the linked_list class which works differently. 并具有工作原理不同的linked_list类的专业化。 Can anyone tell me if this is possible and, if so, how to do it? 谁能告诉我这是否可行,如果可以,怎么办?

[EDIT] [编辑]

template<typename T, list_node T::* node = nullptr> struct linked_list
{
};

followed by: 其次是:

template <typename T> struct linked_list<T, nullptr>
{
};

gives me an error in VS2013: 在VS2013中给我一个错误:

error C2754: 'linked_list' : a partial specialization cannot have a dependent non-type template parameter 错误C2754:“ linked_list”:部分专业化不能具有相关的非类型模板参数

Should this be legal under the standard or have I misunderstood the answer below? 根据标准,这应该合法吗?还是我误解了以下答案?

To allow for one template argument you need to default the second one to something, eg nullptr : 要允许使用一个模板参数,您需要将第二个默认为默认值,例如nullptr

template<typename T, list_node T::* node = nullptr> class linked_list;

Now you can specialize linked_list<T, nullptr> template that is used when the second template argument is nullptr : 现在,您可以专门linked_list<T, nullptr>当第二个模板参数为nullptr时使用的linked_list<T, nullptr>模板:

template<typename T> class linked_list<T, nullptr>;

The above specialization does not work. 上面的专业化无效。 An alternative way to specialize (complete working example): 专业化的另一种方法(完整的工作示例):

struct list_node {};

struct X { list_node node; };

template<typename T, list_node T::*P, bool Special>
struct linked_list_ {};

template<typename T, list_node T::*P>
struct linked_list_<T, P, true> {};

template<typename T, list_node T::*P = nullptr>
struct linked_list
    : linked_list_<T, P, static_cast<list_node T::*>(nullptr) == P>
{};

int main() {
    linked_list<X, &X::node> a; // uses linked_list_<T, P, false>
    linked_list<X> b;           // uses linked_list_<T, P, true>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM