【问题标题】:Is there a way to static_assert a variable reference given in a template parameter?有没有办法静态断言模板参数中给出的变量引用?
【发布时间】:2022-06-15 23:19:18
【问题描述】:
struct Config 
{
    int version = 1; 
};

template<Config& config /* , ... */>
struct Peripheral
{
    const Config config_ = config;
    static_assert(config_.version > 1, "Config version must be greater than 1");
    /* ... */
};

Config myConfig;

int main()
{
    myConfig.version = 5;
    Peripheral<myConfig> peripheral;
}

我想在编译时检查给我的模板的配置是否正确。

所以我试图将我的引用转换为一个常量实例,以便尝试在我的 static_assert 中使用它,但我收到错误:'invalid use of non-static data member ...'

在这种情况下,有没有办法在编译时检查非类型参数的值?

【问题讨论】:

  • 不,编译后变量可能会改变
  • 您对 myConfig.version 进行了更改,该更改仅在运行时可见。即使在原则上,您如何期望它成为编译时static_assert 的有效参数?

标签: c++ templates metaprogramming compile-time static-assert


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
相关资源
最近更新 更多