是否可以将`constexpr`模板变量作为正式模板参数的默认值
Is It Possible to Use a `constexpr` Template Variable as the Default for a Formal Template Argument
使用clang 3.6.0,我无法编译以下代码示例。
#include <type_traits>
template <typename T> constexpr bool IS_SCALAR = ::std::is_scalar<T>::value;
template <typename T, bool = IS_SCALAR<T>>
struct Class_Breaks
{
};
template <typename T, bool = ::std::is_scalar<T>::value>
struct Class_Works
{
};
void function()
{
Class_Breaks<int> break_error;
Class_Breaks<int, IS_SCALAR<int>> breaks_ok;
Class_Works<int> ok;
}
但是,返回以下错误消息:
1> [ 66%] Building CXX object CMakeFiles/Core.dir/tests.cpp.obj
1>D:ProjectsCoreCoretests.cpp(4,30): error : non-type template argument is not a constant expression
1> template <typename T, bool = IS_SCALAR<T>>
1> ^
1> D:ProjectsCoreCoretests.cpp(16,18) : note: while checking a default template argument used here
1> Class_Breaks<int> break_error;
1> ~~~~~~~~~~~~~~~~^
1> 1 error generated.
,如@StenSoft所述,这是一个已知的错误。如果您需要使其正常工作,因为您要用作默认值的constexpr
模板变量,则可以将默认值包装到std::intergral_constant
:
template<
typename T,
bool = std::integral_constant< bool, IS_SCALAR<T> >::value
>
实时示例
这不是在Clang 3.7中固定的。丹尼尔·弗雷(Daniel Frey)提到的错误报告与constexpr函数有关(现在确实有效),但不能可变模板。
相关文章:
- 当给定默认值时,为什么此模板参数推导失败
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 在 c++ 中,如果我创建一个接受一个具有默认值的参数的构造函数 - 它会用作默认(空)构造函数吗?
- 为什么无法在可变参数模板中将尾随模板参数指定为默认值?
- 可变参数模板和具有继承的默认值
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 在子类函数覆盖中省略具有默认值的参数
- 函数作为具有默认值的参数
- 具有另一个具有默认值的模板参数的模板推导
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 可以通过常量引用返回默认参数的值吗?
- 对 const 引用参数使用默认值会导致崩溃
- C ,构造器中允许的参考参数默认值
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- QInput对话框参数默认值
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?