如何在模板变量定义中引入static_assert
How to introduce static_assert into template variable definition
如何将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;
}
但是对于不可移动的对象,用这种方式构造值对象是不可能的。
使用逗号操作符,我不能在形式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
就好了。
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{};
}
或者检查直接出现在变量template中:
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{};
}
相关文章:
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 收到错误"invalid use of non-static data member 'stu::n' "
- LNK1104:无法打开libpjproject-i386-Win32-vc14-Debug-Static.lib
- 我应该在 C++ 中何时/为什么使用 STATIC?
- 在VS2019项目中集成ImageMagick:x64-windows-static library
- 如何在 assert() 和 static_assert() 之间调度,如果在 constexpr 上下文中依赖?
- 如何处理Boost Spirit X3导致Visual Studio 2019 "static initialization order fiasco"?
- 我关于函数"Assert"的C++代码有问题
- "static char __ = []() -> char"的含义
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- 无法在 DLL 中链接 SDL2-static.lib
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- assert() 在发布模式下充当标识函数吗?
- 如何编写一个接受如下断言消息的自定义断言函数:assert(false) << "assertio
- C++线程"Call to non-static member function without an object argument"
- 出现这种错误的原因是什么"invalid use of non-static data member "
- static是如何使用ClassA::m_variable处理所有类对象的
- LNK2001:未解析的外部符号public:static类std::vector
- static assert - C++ concepts vs static_assert