看一下这段代码(godbolt):
#include <type_traits>
#include <memory>
#include <cstdlib>
using namespace std;
template<auto L, class T = decltype(L)>
using constant = integral_constant<T, L>;
int main()
{
unique_ptr<void, constant<&free>> p1;
unique_ptr<void, constant<free>> p2; // <-- MSVC refuses to compile this line
return 0;
}
为什么 MSVC 拒绝编译这个高亮行?这段代码有效吗?
MSVC 的输出结果是:
<source>(13): error C2975: 'L': invalid template argument for 'constant', expected compile-time constant expression
<source>(7): note: see declaration of 'L'
::free
和std::free
可以编译通过,因此某些编译器可能会用编译器内置函数替换free
函数。 - Artyerusing namespace std;
并相应地在unique_ptr
前加上std::
限定符也可以使程序编译通过。free
可能只是别名C库版本,它具有C语言链接,但这对于auto
非类型模板参数来说不重要(但尝试将具有语言链接的函数指针分配给C ++语言链接的函数地址时会产生问题,也许这会导致此处的明显错误行为)。 - dfrib