【发布时间】:2018-05-21 03:42:05
【问题描述】:
更新 2:
这已在 VS 2019 Preview 16.1 Preview 1 中得到修复。
更新:
我已在visualstudio.com 提交错误报告。
所以我开始研究 C++ 的模板,当我试图阻止使用 static_assert 编译模板类时遇到了这个问题。
基本上,static_assert 错误在 VS2017 上使用 C++ 语言标准:ISO C++17 标准 (/std:c++17) 位于 lambda 内时不会触发。
我也在 gcc-7 上使用 -std=c++17 进行了尝试,并触发了错误。这是 VS2017 上的错误还是我遗漏了什么?
代码示例:
#include <iostream>
#include <string>
#include <type_traits>
template<typename T, typename Enable = void>
class IntegralContainer
{
static_assert(std::is_integral<T>::value, "Type must be an integral!");
};
template<typename T>
class IntegralContainer<T, typename std::enable_if< std::is_integral<T>::value >::type >
{
private:
T _value;
public:
IntegralContainer(T value)
: _value(value)
{
}
};
int main()
{
IntegralContainer<int> int_container(1);
// static_assert message is shown here.
// > error C2338: Type must be an integral!
// IntegralContainer<std::string> str_container;
[]() {
// static_assert is not triggered here.
IntegralContainer<std::string> str_container;
}();
std::cout << "Hello World!\n";
return 0;
}
【问题讨论】:
-
来自Godbolt,看起来它甚至在触发错误之前优化了lambda的内容(这将是一个错误)......
-
但是如果你给主模板一个带有副作用的默认构造函数,这些副作用确实会发生。
标签: c++ visual-c++ c++17