依赖于模板的错误
Template dependent false
我有一个类模板,不能直接使用,只允许专业化。我想使用static_assert
来显示有意义的错误消息。我不能只键入static_assert(false, "error");
,因为false
不依赖于值,即使从未使用过模板,编译器也可能显示错误消息。
我的解决方案:
template<class>
struct AlwaysFalse : std::false_type{};
#define DEPENDENT_FALSE(arg) AlwaysFalse<decltype(sizeof(arg))>::value
template<class T>
struct Foo{
static_assert(DEPENDENT_FALSE(T), "You must use specialization!");
};
template<int i>
struct Bar{
static_assert(DEPENDENT_FALSE(i), "You must use specialization!");
};
但我不确定是否实现DEPENDENT_FALSE
。因为MSVC不将sizeof(arg)
视为依赖于模板的表达式(与GCC不同(,但decltype(sizeof(arg))
是可以的。
有人能用标准来解释这种行为吗?它是便携式的吗?
这:
#define DEPENDENT_FALSE(arg) AlwaysFalse<decltype(sizeof(arg))>::value
实际上并不是依赖于的。decltype(sizeof(arg))
总是size_t
,它实际上并不以任何方式依赖于arg
(更广泛地说,这里是一个从不依赖于类型的表达式列表(。由于它不是依赖的,编译器完全能够看到DEPENDENT_FALSE(T)
是false
,并触发该static_assert
。
你想要的只是:
#define DEPENDENT_FALSE(arg) AlwaysFalse<decltype(arg)>::value
也就是说,丢弃sizeof
。现在依赖于。
这不会直接适用于int
,因为这也不会是依赖的(decltype(i)
只是int
,我们现在需要一些值依赖的东西(。为此,您可以将其封装在一个积分常数中:
template<class T>
struct Foo{
static_assert(AlwaysFalse<T>::value, "You must use specialization!");
};
template<int i>
struct Bar{
static_assert(AlwaysFalse<std::integral_constant<int, i>>::value, "You must use specialization!");
};
也许有以下想法:
template<typename T>
struct AlwaysError
{
AlwaysError<T>()
{
std::cout << T::value << std::endl;
static_assert( T::value, "You must use specialization!");
}
};
template <typename T>
struct Foo: public AlwaysError<Foo<T>>
{
static constexpr bool value = false;
};
template <>
struct Foo<int>{};
int main()
{
//Foo<double> d; // error message as expected
Foo<int> i; // specialized, compiles!
}
断言消息包含文本以及应该专门化的类型。希望它能有所帮助!
在C++17上工作的解决方案。不幸的是,我只有C++11
template<auto>
constexpr bool dependentFalseHelper(){
return false;
}
template<class>
constexpr bool dependentFalseHelper(){
return false;
}
#define DEPENDENT_FALSE(arg) (dependentFalseHelper<arg>())
相关文章:
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 为什么内存屏障依赖于变量?
- 反转依赖于 end() 的迭代器
- 编译依赖于 QTCore 库的 WASM
- 如何添加依赖于类本身的模板成员变量
- 初始化依赖于子类的继承类的常量类成员
- Makefile 创建两个库 - 一个依赖于另一个
- 对于BTreeMap和其他依赖于Ord的东西,是否有等效于C++比较器对象?
- 类成员函数参数列表是否可以依赖于模板参数?
- 依赖于类成员属性的类实例成员
- 如何定义依赖于参数包转换的函数的返回类型
- 依赖于模板的错误
- 依赖于特定类类型的C++模板方法
- FBString 的小字符串优化是否依赖于未定义的行为?
- 如何修复"没有依赖于模板参数的参数'glGenVertexArrays'......"C++ 中的错误
- C++ 错误:"没有依赖于模板参数的'setw'参数
- G++:错误:没有依赖于模板参数的参数'pow',因此必须提供'pow'声明 [-fallowive]
- GCC 为依赖于默认构造函数的模板化类中的静态数据成员提供"undefined reference"错误
- windows上的boost.asio错误代码依赖于平台
- 如何解决 - 错误:没有依赖于模板参数的"退出"参数