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

时间:2015-05-15 13:14:04

标签: c++ c++14

使用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:\Projects\Core\Core\tests.cpp(4,30): error : non-type template argument is not a constant expression
1>  template <typename T, bool = IS_SCALAR<T>>
1>                               ^
1>  D:\Projects\Core\Core\tests.cpp(16,18) :  note: while checking a default template argument used here
1>          Class_Breaks<int> break_error;
1>          ~~~~~~~~~~~~~~~~^
1>  1 error generated.

2 个答案:

答案 0 :(得分:4)

如@StenSoft所述,它是known bug。如果您需要使其工作,因为您有一个constexpr模板变量,您希望将其用作默认值,则可以将默认值包装为std::intergral_constant

template<
    typename T,
    bool = std::integral_constant< bool, IS_SCALAR<T> >::value
>

Live example

答案 1 :(得分:0)

这在clang 3.7中没有修复。 Daniel Frey提到的错误报告涉及constexpr函数(现在可以工作)但不是变量模板。