模板参数可以是表达式吗?

3 c++ templates expression

我想做这个:

template<T>
bool AssertThrows() {
  try {
    T; // T is an expression, so evaluate it here
    return false;
  } catch(...) {
    return true;
  }
}

int main() {
  bool throws = !AssertThrows<5 + 2>();
  return !throws;
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用:我得到的只是这些编译器错误:

$ clang++ a.cc
a.cc:1:10: error: unknown type name 'T'
template<T>
         ^
a.cc:4:5: error: use of undeclared identifier 'T'
    T; // T is an expression
    ^
2 errors generated.
Run Code Online (Sandbox Code Playgroud)

是否可以将表达式作为模板参数?

Dav*_*eas 6

模板在编译时处理,这意味着你只能使用常量表达式,其中没有一个可以抛出,所以简单的答案就是你无法在那里做你想做的事情.

虽然我在大多数情况下都反对宏,但这是它们有意义的少数几个地方之一,如果你看一下测试框架,你会发现宏是这个特定问题的通用解决方案.