如何在模板变量定义中引入static_assert

Ori*_*ent 2 c++ static-assert type-traits variable-templates c++14

如何引入static_assert模板变量定义?

我的尝试是使用 lambda 函数:

#include <type_traits>
#include <utility>

#include <cstdlib>

namespace
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"

template< typename F >
F f = ([] () { static_assert(std::is_default_constructible< F >{}); }(), F{});

#pragma clang diagnostic pop
}

struct L
{
    L() = default;
    L(L const &) = delete;
    L(L &&) = delete; 
};

int
main()
{
    static_cast< void >(f< L >);
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

但对于不可移动的对象,不可能以这种方式构造值对象。

使用逗号运算符我无法在 form 中执行值初始化F f = ([] () { static_assert(std::is_default_constructible< F >{}); }(), {});

我无法在表单中使用额外的模板参数, typename = decltype([] () { static_assert(std::is_default_constructible< F >()); }),因为它是一个错误lambda expression in an unevaluated operand

通过 SFINAE 禁用实例化并不是解决方案。我确实需要static_assert明确地告诉用户有关错误的信息。

static_assert如果能返回void或者那就太好了bool

Jon*_*ely 5

template<typename T>
struct require_default_constructible {
  static_assert(std::is_default_constructible<T>{}, "is default constructible");
  using type = T;
};

namespace
{
template< typename F >
  typename require_default_constructible<F>::type f{};
}
Run Code Online (Sandbox Code Playgroud)

或者,检查直接出现在变量模板中:

template<typename T, bool B>
struct check {
  static_assert(B, "???");
  using type = T;
};

namespace
{
template< typename F >
  typename check<F, std::is_default_constructible<F>::value>::type f{};
}
Run Code Online (Sandbox Code Playgroud)