Modern C++ - auto
#include <iostream>
#include <vector>
#include <list>
#include <deque>
#include <map>
#include <set>
#include<algorithm>
using namespace std;
// Modern C++ (C++11 부터 나온 아이들)
// auto
class Knight {
public:
int _hp;
};
template<typename T>
void Print(T t) {
cout << t << endl;
}
int main()
{
//int a = 3;
//float b = 3.14f;
//double c = 1.23;
//Knight d = Knight();
//const char* e = "LeeSY";
// 컴파일 단계에서 자동으로 추론하여 데이터형을 정함
auto a = 3;
auto b = 3.14f;
auto c = 1.23;
auto d = Knight();
auto e = "LeeSY";
// auto는 조커카드 느낌이다~
// 형식 연역 (type deduction)
// -> 말이 되게 잘 맞춰봐~ (추론)
// 추론 규칙은 생각보다 복잡해질 수 있다.
auto f = &d;
const auto test1 = b; // 더 이상 안 바꿀거임
auto* test2 = e; // auto를 const char로 바꿔줌
// 주의
// 기본 auto는 const, & 무시 한다.
int& reference = a;
const int cst = a;
auto testA = reference; // 레퍼런스로 선언되지 않고 기본 int로 선언됨
auto testB = cst; // const int로 선언되지 않고 기본 int로 선언됨
Print(e);
Print(c);
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for (vector<int>::size_type i = 0;i < v.size();i++) {
auto& data = v[i]; // &를 통해 힌트를 줘야함
data = 100;
}
// 기존의 타입은 버리고 auto만 사용해도 될라나??
// -> 호불호가 갈린다.
// -> 타이핑이 길어지는 경우에는 사용하는 것이 좋다.
// -> 그러나 가독성 측면에서 손해를 봄. 데이터 형을 알아내는 것이 어려워짐.
// -> 일반적으로는 auto보단 일반적인 명시적 선언을 사용하고 타이핑이 길어질 경우 auto를 사용하는 편이 좋다.
// ex) vector<int>::iterator, pair<map<int,int>::iterator,bool>
return 0;
}
Reference
この問題について(Modern C++ - auto), 我々は、より多くの情報をここで見つけました https://velog.io/@sansam41/Modern-C-autoテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol