是否可以将`constexpr`模板变量作为正式模板参数的默认值

Is It Possible to Use a `constexpr` Template Variable as the Default for a Formal Template Argument

本文关键字:参数 默认值 constexpr 是否 变量      更新时间:2023-10-16

使用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函数有关(现在确实有效),但不能可变模板。