- 이 글에서는
C++98
부터C++20
까지 다양한C++
표준 버전에서 템플릿 타입 유추(Deduction Guide
) 기능을 어떻게 구현할 수 있는지를 비교합니다. - 특히
"const char*"
이 입력되었을 때 내부적으로std::string
으로 처리되도록 하는Holder
클래스 예제를 기준으로 각 버전별 코드를 설명합니다.
-
cpp
#include <string> #include <iostream> template<typename T> class Holder { public: Holder(T value) { std::cout << "Generic Holder: " << value << std::endl; } }; template<> class Holder<std::string> { public: Holder(const char* value) { std::cout << "Specialized Holder<std::string>: " << value << std::endl; } }; int main() { Holder<int> h1(42); Holder<std::string> h2("hello"); // 직접 타입 명시 필요 }
- 자동 유추 기능이 없기 때문에 사용자가 명시적으로 타입을 지정해야 합니다.
-
cpp
#include <string> #include <iostream> template<typename T> class Holder { public: Holder(T value) { std::cout << "Generic Holder: " << value << std::endl; } }; // 헬퍼 함수 제작 template<typename T> Holder<T> make_holder(T value) { return Holder<T>(value); } Holder<std::string> make_holder(const char* value) { return Holder<std::string>(std::string(value)); } int main() { auto h1 = make_holder(42); // Holder<int> auto h2 = make_holder("hello"); // Holder<std::string> }
make_holder()
와 같은 헬퍼 함수를 통해Deduction Guide
와 유사한 효과를 낼 수 있습니다.- 단, 일반 생성자 방식(
Holder h(...)
)은 사용할 수 없습니다.
-
cpp
#include <string> #include <iostream> template<typename T> class Holder { public: Holder(T value) { std::cout << "Holder<" << typeid(T).name() << ">: " << value << std::endl; } }; Holder(const char*) -> Holder<std::string>; // Deduction Guide int main() { Holder h1(42); // Holder<int> Holder h2("hello"); // Holder<std::string> }
- 생성자 인자를 기반으로 자동 템플릿 타입 유추가 가능합니다.
-
cpp
#include <string> #include <iostream> #include <concepts> template<typename T> class Holder { public: Holder(T value) { std::cout << "Holder<" << typeid(T).name() << ">: " << value << std::endl; } }; Holder(const char*) -> Holder<std::string>; template<std::integral T> Holder(T) -> Holder<int>; template<std::floating_point T> Holder(T) -> Holder<double>; int main() { Holder h1("hello"); // Holder<std::string> Holder h2(10); // Holder<int> Holder h3(3.14f); // Holder<double> }
requires
또는concepts
를 활용하여 조건에 따라 다른 타입으로 유도할 수 있습니다.
-
기능 C++98
C++11/14
C++17
C++20
템플릿 자동 유추 ❌ 🔸 함수 통해 우회 ✅ 생성자 인자 기반 유도 ✅ + 조건 분기 가능 타입 유추 ( const char*
→std::string
)수동 특수화 make_*
함수Deduction Guide
Deduction Guide
+requires
코드 간결성 ❌ 복잡 🔸 함수 우회 ✅ 깔끔 ✅ 더 정교함 -
C++
버전 별로 타입 유추 기능은 계속 진화 중입니다. 😕 😵 🤔 🚀 👽