【问题标题】:Inputs of a method depending on the template structure方法的输入取决于模板结构
【发布时间】:2022-01-12 09:53:53
【问题描述】:
template <typename Stru_>
    class templateClasse{
    public:
    
      using stru = Stru_;
    
      static void method_0(int sk, int sl){
        printf("class templateClass method_0 sk: %d sl: %d\n", sk, sl);
      }
    
      static void method_1(int a){
        if (stru::isvec){
          method_0(0, a);
        } else{
          method_0(a, 0);
        }
      }
    };

我想根据 bool stru::isvec 更改method_0 中的输入,如代码所示,同时,我希望在编译期间选择if (stru::isvec) else 分支而不是运行时。我的问题是:

  1. 这段代码在编译时是否选择了method_0
  2. 代码只有在这两个方法前加上关键字static才编译成功。为什么static在这种情况下有效?通常,我对static的理解是这样的:

这些静态变量存储在静态存储区,而不是在 堆栈。

我知道当我使用static const int tmp = 50; 时,这个tmp 是在编译时计算的。那么static可以粗略理解为帮助编译时计算的关键字吗?

  1. 在这种情况下我们还有其他解决方案吗?

提前致谢!

【问题讨论】:

  • 关键字static 有多种含义,具体取决于您使用它的位置。在类定义中,它表明类的成员不会与类的任何实例相关联,因此将具有延长的生命周期。它与堆栈/堆/只读内存部分/等无关。

标签: c++ templates static metaprogramming


【解决方案1】:
  1. 这段代码在编译时是否选择了method_0

不,调度发生在运行时。

您可以使用constexpr if (since C++17) 使调度在编译时执行。

void method_1(int a){
  if constexpr (stru::isvec){
    method_0(0, a);
  } else{
    method_0(a, 0);
  }
}
  1. 只有在这两个方法前加上关键字static,代码才编译成功。

不,您不必这样做。这是一个附带问题;在类定义中static 用于声明未绑定到类实例的static members

LIVE

使用 C++11,您可以使用 SFINAE 执行重载。例如

template <typename T = Stru_>
typename std::enable_if<T::isvec>::type method_1(int a){
   method_0(0, a);
}
template <typename T = Stru_>
typename std::enable_if<!T::isvec>::type method_1(int a){
   method_0(a, 0);
}

LIVE

【讨论】:

  • 感谢您的回答。我们是否还有其他适用于 C++ 11 的方法来使调度在编译时执行?
  • @picklesmithy129 答案已修改。
猜你喜欢
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 2015-01-08
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
相关资源
最近更新 更多