简体   繁体   English

C++ class 模板与非类型参数取决于使用 C++11 的类型参数问题

[英]C++ class template with non-type parameter depending on type parameter problem using C++11

I understand that the normal means in C++ of controlling at compile time which class template member functions are included/excluded is through partial specialization.我了解 C++ 中在编译时控制包含/排除 class 模板成员函数的正常方法是通过部分专业化。 I have a class template which has a type parameter and a non-type parameter depending on the type parameter.我有一个 class 模板,它有一个类型参数和一个非类型参数,具体取决于类型参数。 When the non-type parameter is a certain value I want certain member functions of a class template to be part of the instantiation of the class template but not others.当非类型参数是某个值时,我希望 class 模板的某些成员函数成为 class 模板实例化的一部分,而不是其他模板。 The normal way of doing this is to code the primary template to include certain member functions and then to code a partial specialization of the primary template with a different set of member functions.执行此操作的正常方法是对主模板进行编码以包含某些成员函数,然后使用一组不同的成员函数对主模板的部分特化进行编码。 But because of the rule which says:但是由于规则说:

"Non-type template argument cannot specialize a template parameter whose type depends on a parameter of the specialization" I can not do this. “非类型模板参数不能专门化其类型取决于专门化参数的模板参数”我不能这样做。 Is there a way around this?有没有解决的办法? Simple example code would look like:简单的示例代码如下所示:

  template 
    <
    class T, 
    T * v
    >
  struct  AClassTemple
    {
    void SomeMemberFunction() { code etc. }
    void AnotherMemberFunction() { code etc. }
    };

When 'v' is a nullptr I want my class template to not include AnotherMemberFunction and its code, which assumes a value for 'v' which is not a nullptr.当'v'是一个nullptr时,我希望我的class模板不包括AnotherMemberFunction及其代码,它假定'v'的值不是nullptr。 I can not partially specialize the class template by specifying:我不能通过指定来部分专门化 class 模板:

  template 
    <
    class T 
    >
  struct  AClassTemple<T,nullptr>
     {
     };

etc. else I get a compiler error reflecting the rule above.等等,否则我会收到反映上述规则的编译器错误。

The following should do what you want:以下应该做你想要的:

#include <type_traits>

template<class T, T *v>
struct AClassTemple {
    template<T *w = v, class = std::enable_if_t<w != nullptr>>
    void SomeMemberFunction() {}

    template<T *w = v, class = std::enable_if_t<w != nullptr>>
    void AnotherMemberFunction() {}
};

int main() {
    constexpr static char c = '0';
    AClassTemple<int, nullptr> a{};
    AClassTemple<const char, &c> b{};

    // a.SomeMemberFunction(); // will not compile
    b.SomeMemberFunction();
}

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

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