gpt4 book ai didi

c++ - 如何在函数使用时使 static_assert 失败

转载 作者:行者123 更新时间:2023-11-30 05:03:09 25 4
gpt4 key购买 nike

当我尝试打印一个类的实例时,我希望编译器发出警告,比方说 T2。在 VS2013+ 中我可以使用:

template <typename T = float>
std::ostream & operator<<(std::ostream & os, const T2 & t2) {
static_assert(std::is_integral<T>::value, "Fail in << for T2");
return os;
}

但是,这在 VS2012 中不起作用(错误 C4519:默认模板参数只允许在类模板上使用)。有什么想法可以在 VS2012 中实现吗?

最佳答案

VS2012 对 C++11 的支持不完整。支持函数模板的默认模板参数,作为 C++11 的特性 starting with VS2013 .

也许你可以试试这个,但它也使用了一些 C++11 特性:

template <typename T>
auto operator<<(std::ostream & os, T const& t2) ->
typename std::enable_if<std::is_same<T, T2>::value, std::ostream&>::type
{
static_assert(false, "Fail in << for T2");
return os;
}

如果这也不起作用,我会优雅地降级为像 VS2012 这样的陈旧废话并完成它。

#if _MSC_VER < 1800
std::ostream& operator<<(std::ostream & os, T2 const& t2); // will fail at link time
#else
. . .
#endif

关于c++ - 如何在函数使用时使 static_assert 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49557729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com