using

2025. 3. 21. 19:55C++

1. 특정 클래스나 함수만 using 선언하기

특정 클래스나 함수만 using 선언 * 코드가 더 명확하고 충돌을 방지

#include <iostream>
using std::cout;  // std::cout만 사용
using std::cin;   // std::cin만 사용
using std::endl;  // std::endl만 사용

int main() {
    int x;
    cout << "Enter a number: "; 		// std::cout
    cin >> x;					// std::cin
    cout << "You entered: " << x << endl;	// std::endl
    return 0;
}

2. 사용자 정의 네임스페이스

using을 사용하여 자신이 정의한 네임스페이스에서도 간편하게 객체나 함수를 사용

#include <iostream>

namespace myNamespace {
    int x = 10;
    void print() {
        std::cout << "Value of x: " << x << std::endl;
    }
}

using myNamespace::print;  // myNamespace의 print 함수
using myNamespace::x;      // myNamespace의 x 변수

int main() {
    print();					// myNamespace::print()
    std::cout << "x is: " << x << std::endl;	// myNamespace::x
    return 0;
}

3. 네임스페이스 별칭 (Namespace Aliasing)

네임스페이스에 별칭을 붙여서 더 짧고 간편하게 사용

#include <iostream>

namespace ns = std;  // std 네임스페이스를 ns로 사용

int main() {
    ns::cout << "Hello, World!" << ns::endl;	// std 대신 ns 사용
    return 0;
}

4. 템플릿의 using 선언

템플릿에서도 using을 사용

#include <iostream>
#include <vector>

template <typename T>
using Vec = std::vector<T>;		// std::vector<T>를 Vec로 지정

int main() {
    Vec<int> v;				// std::vector<int>를 Vec<int>로 사용
    v.push_back(10);
    std::cout << v[0] << std::endl;	// 10을 출력
    return 0;
}

5. 조건부 using

C++17부터는 조건부로 using 선언을 사용

#include <iostream>

#if defined(_MSC_VER)
    using std::cout;		// Windows에서는 std::cout 사용
#else
    using std::cerr;		// 다른 OS에서는 std::cerr 사용
#endif

int main() {
    cerr << "Hello from the platform!" << std::endl;
    return 0;
}

 

'C++' 카테고리의 다른 글

힙 / 스택  (0) 2025.03.25
cin  (0) 2025.03.21
limits  (0) 2025.03.21
iomanip  (0) 2025.03.20
string  (0) 2025.03.20