In my work the use of const_cast is under some circumstances unavoidable.Now I have to const_cast some pretty complicated types and actually I don't want to write all this type clutter in the const_cast<Clutter> expressions, especially if Clutter is very long.My first idea was to write const_cast<>(myType), but my compiler cannot deduce the non-const type of myType. So I thought about helping my compiler and I deviced the following approach, which compiles. #include <stdlib.h>#include <iostream>int main(int, char**) { const int constVar = 6; using T = typename std::remove_cv<decltype(constVar)>::type; auto& var = const_cast<T&>(constVar); var *= 2; std::cout << &constVar << " " << &var << "\n"; // Same address! std::cout << constVar << " " << var << "\n"; return EXIT_SUCCESS;}Unfortunately, the program gives me the output 6 12 instead of the expected 6 6, which I really didn't understand?What is wrong with my approach? 解决方案 From the documentation of const_cast: So what you have is undefined behavior.Also of interest is this note from cv type qualifiers. 这篇关于使用 const_cast 进行自动类型推导不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-01 02:15