问题描述
考虑下面的代码有一个类型错误。我试图返回一个指向 double 的指针作为指向 int 的指针,目的是它不会编译。问题是错误信息很垃圾。
template <typename T>
int * Foo(T & t){
using Bar = T *;
Bar k = &t;
return k;
}
int main(){
double i = 10;
Foo(i);
}
来自编译器的错误信息是 at godbolt
example.cpp
<source>(9): error C2440: 'return': cannot convert from 'Bar' to 'int *'
<source>(9): note: Types pointed to are unrelated; conversion requires reinterpret_cast,C-style cast or function-style cast
<source>(15): note: see reference to function template instantiation 'int *Foo<double>(T &)' being compiled
with
[
T=double
]
Compiler returned: 2
这让我抓狂,因为 Bar 没有告诉我问题是什么,因为它取决于模板参数。 Clang 扩展了错误消息中的别名。 aka 'double *'
。见godbolt again
<source>:9:12: error: cannot initialize return object of type 'int *' with an lvalue of type 'Bar' (aka 'double *')
return k;
^
<source>:15:5: note: in instantiation of function template specialization 'Foo<double>' requested here
Foo(i);
^
1 error generated.
Compiler returned: 1
是否有编译器标志或我可以做些什么来通过类型别名制作 Visual Studio 报告?令人讨厌的是,如果我内联类型别名,我会收到一条不错的错误消息,但这会妨碍编写干净的代码。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)