Visual C:模板类中的自定义错误消息

Visual C: Custom Error Message in Template Class

本文关键字:自定义 错误 消息 Visual      更新时间:2023-10-16

下面的代码失败(如预期(。困扰我的是错误信息。它没有明确说明问题出在哪里。我本以为会有“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 };
}