Visual C:模板类中的自定义错误消息
Visual C: Custom Error Message in Template Class
下面的代码失败(如预期(。困扰我的是错误信息。它没有明确说明问题出在哪里。我本以为会有“cannot convert from const char* to int”
这样的东西。相反,它说"cannot convert from 'initializer list' to 'B<int>'"
,当涉及其他复杂类型时,它就不那么清楚了。
如何添加自定义错误消息?实际的课程要复杂得多。
#include <vector>
template< typename T >
class B
{
std::vector<T> v;
public:
B( std::initializer_list<T> il ) : v{ il } {}
};
int main()
{
B<int> b{ "a","b","c" }; // fails with cannot convert from 'initializer list' to 'B<int>'
}
如果您只想有一个std::initializer_list<T>
构造函数,那么您可以做的一件事是提供一个可变模板构造函数,然后在构造函数中有一个提供所需错误消息的static_assert
。这之所以有效,是因为如果您提供std::initializer_list<T>
以外的任何东西,那么构造函数将是更好的匹配,断言将被激发。看起来像
#include <vector>
template< typename T >
class B
{
std::vector<T> v;
public:
B( std::initializer_list<T> il ) : v{ il } {}
template <typename... Args>
// the sizeof...(Args) < 0 is needed so the assert will only fire if the constructor is called
B(Args...) { static_assert(sizeof...(Args) < 0, "This class can only be constructed from a std::initializer_list<T>"); }
};
int main()
{
//B<int> b1{ "a","b","c" }; // uncomment this line to get static_assert to fire
B<int> b2{ 1,2,3 };
}
相关文章:
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 如何在C++中返回自定义类中的分段错误?
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- C++自定义分配器大小参数作为模板参数会引发编译器错误
- Tbb 库:错误:编写自定义类函数而不是 lambda 表达式时,对函数的调用不匹配
- 错误 - 自定义数据类型作为有效负载,带有提升::几何
- 自定义runtime_error,如果我在 #what 中使用#c_str(),则错误输出始终为空
- 自定义预期失败的完整错误消息(boost::spirit::x3)
- C++:自定义数据类型向量错误的队列
- 导致编译错误的自定义预编译标头
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- (C++)我的自定义数组无法初始化(编译错误)
- 自定义Vector2D类中的浮点错误
- Visual C:模板类中的自定义错误消息
- C++ MSVC 中的自定义 STL 分配器错误?
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 带有__PRETTY_UNCTION_的自定义错误处理程序
- 如何在 C(++) 中定义自定义错误代码
- 在V8中从C++代码创建自定义错误类
- 将Windows 7窗口标记为始终位于顶部,包括Win7任务栏(自定义错误)