【问题标题】:How to get the value of a non-type template parameter?如何获取非类型模板参数的值?
【发布时间】:2016-03-06 15:40:34
【问题描述】:

示例如下:

template <int n>
class A { };

class B {
public:
  int foo() {
    return a.n;  // error
  }
private:
  A<10> a;
};

我想在类B中获取实例化类A&lt;10&gt;的非类型模板参数的值,而不是模板A本身,有没有办法做到这一点?或者我应该使用其他一些设计来避免这个问题?

【问题讨论】:

  • @πάνταῥεῖ 但是B 是一个没有名为n 的成员的普通类。
  • 您声明了A&lt;10&gt; a,10 是编译时常量。因此,如果它是一个常数,为什么不在foo 中硬编码数字 10?

标签: c++ templates


【解决方案1】:

您不能像那样访问其他类模板参数。另一个类必须公开它,例如:

template <int n>
class A {
public:
    static const int num = n;
};

然后你可以使用a.num(当然也可以是A&lt;10&gt;::num)访问它

【讨论】:

    【解决方案2】:

    如果无法获取类型配合(通过发布参数值),可以自己用traits类提取:

    template<class> struct A_param; // not defined
    
    template<int N> struct A_param<A<N>> {
        static constexpr int value = N;
    };
    
    // a more general implementation would probably want to handle cv-qualified As etc.
    

    然后使用A_param&lt;decltype(a)&gt;::value

    【讨论】:

      【解决方案3】:

      如果您有成员A&lt;10&gt;,您的 B 类已经知道模板参数。请改用该值。如果模板参数确实没有命名,让A定义一个反映模板参数的成员。

      1 -

      class B {
      public:
        int foo() {
          return n;  
        }
      private:
        const int n = 10;
        A<n> a;
      };
      

      2 -

      template <int n>
      class A { 
      public:
          static const int template_param = n;
      };
      

      【讨论】:

      • 我可以使用decltype 或者类似编译时类型识别的东西来解决这个问题吗?
      • @Jaege 您要解决的具体问题是什么? Decltype 无法访问模板参数。当从模板创建类时, A 只是类名。如果您需要在运行时访问模板参数,则可以使用常量。
      • 我在C++ Primer中做练习16.14,其中定义了一个类模板Screen和一个类Window_mgr。在Window_mgr::clear() 内部,我需要清理屏幕的内容。完整代码为here
      猜你喜欢
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      相关资源
      最近更新 更多