(23条消息) C++ 去掉const_最后冰吻free的博客-CSDN博客_c++ 去掉const
Thu Nov 24 2022 06:06:19 GMT+0000 (Coordinated Universal Time)
Saved by
@leawoliu
#include <iostream>
#include <vector>
template<typename T>
class TypeTraits{
private:
template<typename U> class UnConst{
public:
typedef U Result;
};
template<typename U> class UnConst<const U>{
public:
typedef U Result;
};
public:
typedef typename UnConst<T>::Result NonConstType;
};
template<typename T>
using NonConstType = typename TypeTraits<T>::NonConstType;
template<typename T>
void Func(NonConstType<T> t) {
std::string* nonP = &t; // ok
std::string& nonR = t; // ok
std::cout<<*nonP<<std::endl;
}
// 用于转发函数时,不需要根据参数有无const进行重载函数(函数体实现一样的函数)
template<typename T>
void ForwardFunc(NonConstType<T> t) {
Func<T>(t);
}
void Test(){
const int a = 10;
TypeTraits<const int>::NonConstType noConstVar;
// int& nonConstRef = a; // error not bind const int to int&
// int* nonConstP = &a; // error, invaild conversion from const int* to int
int *p = &noConstVar; // ok
const std::string str("hello");
ForwardFunc<const std::string>(str);
}
int main(){
Test();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
content_copyCOPY
https://blog.csdn.net/CodeHouse/article/details/125920306
Comments