模板参数可以是表达式吗?
Can a template argument be an 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;
}
但这不起作用:我得到的是这些编译器错误:
$ 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.
是否可以将表达式作为模板参数?
模板是在编译时处理的,这意味着你只能使用常量表达式,它们都不会抛出,所以简单的答案是你不能在那里做你想做的。
虽然我反对在大多数情况下使用宏,但这是它们有意义的少数几个地方之一,如果您查看测试框架,您会发现宏是这个特定问题的通用解决方案。
在这种情况下,如果您不介意,可以使用另一个函数来模拟按名称传递的函数
template<typename T>
bool AssertThrows(T t) {
try {
t(); // t contains an expression, so evaluate it here
return false;
} catch(...) {
return true;
}
}
int main() {
bool throws = !AssertThrows([]{ 5 + 2; });
return !throws;
}
模板参数可以是常量表达式,正如David指出的那样。这就是你要找的吗?
template<int Expr>
bool AssertThrows() {
try {
Expr; // Expr is a constant expression that 'is' an int, so evaluate it here
return false;
} catch(...) {
return true;
}
}
int main() {
bool throws = !AssertThrows<5 + 2>();
return !throws;
}
相关文章:
- 概念中的cv限定符需要表达式参数列表
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 使用自动推导的 lambda 参数作为常量表达式
- 编译器是否强制根据模板参数计算表达式?
- 错误:参数中无效地使用了无效表达式
- 将折叠表达式传递给可变参数模板
- 为什么带有指针子对象的文字类类型的 constexpr 表达式不能是非类型模板参数
- C++: priority_queue:模板参数中的 lambda 表达式
- 容器如何处理 lambda 表达式的参数
- 在C++ Lambda 表达式中,为什么人们更喜欢按值捕获而不是作为参数传递?
- 整体模板参数。错误:在常量表达式中使用'this'
- 我可以std::在fold表达式中转发参数吗
- 折叠表达式模板参数推导/替换失败
- 折叠表达式和参数包:static_assert 内 Args&& 和 Args 之间的区别
- C++:从捕获函数参数的函数返回 lambda 表达式
- 是否可以使用带有模板化参数的特征块表达式作为左值?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 表达式参数在 C++ 中有什么用
- 类表达式参数定义不正确