[C++] std::any : 어떤 타입이든 담는 값

[C++] std::any : 어떤 타입이든 담는 값

안녕하세요. 이번 글에서는 C++17에서 추가된 std::any에 대해 알아보겠습니다.

C++은 정적 타입 언어라서 변수 하나에는 정해진 타입의 값만 담을 수 있습니다. 그런데 설정 값 저장소, 메시지에 붙는 부가 데이터처럼 어떤 타입이 들어올지 미리 정할 수 없는 값을 다뤄야 할 때가 있습니다. 예전에는 void*를 쓰거나 공통 부모 클래스를 만들어 해결했지만, 타입 안전성이 떨어지고 메모리 관리도 직접 해야 했습니다. std::any는 복사 가능한 어떤 타입의 값이든 하나 담을 수 있고, 꺼낼 때 타입을 검사해 주는 타입 안전한 컨테이너입니다.

기본 사용법

헤더는 <any>입니다. 값을 대입하면 그 값의 타입과 함께 저장되고, 꺼낼 때는 any_cast<T>로 저장된 타입을 지정합니다. type()은 현재 저장된 값의 std::type_info를 돌려줍니다.

#include <any>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    any value = 10;                         // int
    cout << any_cast<int>(value) << "\n";

    value = 3.14;                           // double
    cout << any_cast<double>(value) << "\n";

    value = string("hello");                // string
    cout << any_cast<string>(value) << "\n";

    cout << boolalpha << (value.type() == typeid(string)) << "\n";   // 저장된 타입 확인
}

실행 결과

10
3.14
hello
true

같은 변수 value에 int, double, string을 차례로 대입했습니다. 대입할 때마다 이전 값은 소멸되고 새 타입의 값이 저장됩니다.

주요 함수

함수설명
any_cast<T>(any)값(또는 참조)으로 꺼냄. 타입이 다르면 std::bad_any_cast 예외
any_cast<T>(any*)포인터로 꺼냄. 타입이 다르거나 비어 있으면 nullptr
has_value()값이 들어 있으면 true
type()저장된 값의 typeid. 비어 있으면 typeid(void)
reset()저장된 값을 소멸시키고 비움
emplace<T>(args…)기존 값을 버리고 T를 제자리 생성
make_any<T>(args…)T를 생성해 담은 any를 만들어 반환

값 꺼내기 : any_cast

any_cast는 인자 형태에 따라 동작이 다릅니다. any 객체를 넘기면 타입이 맞지 않을 때 bad_any_cast 예외를 던지고, any의 주소를 넘기면 예외 대신 nullptr을 돌려줍니다. 타입이 확실하지 않은 경우에는 포인터 형태가 다루기 편합니다. 또 any_cast<T&>처럼 참조 타입을 지정하면 복사 없이 저장된 값을 직접 수정할 수 있습니다.

#include <any>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    any value = 42;

    // 1) 값으로 꺼내기 : 타입이 틀리면 bad_any_cast 예외
    try
    {
        string s = any_cast<string>(value);
    }
    catch (const bad_any_cast& e)
    {
        cout << "예외: " << e.what() << "\n";
    }

    // 2) 포인터로 꺼내기 : 타입이 틀리면 nullptr
    if (int* p = any_cast<int>(&value))
        cout << "int 값: " << *p << "\n";

    if (string* p = any_cast<string>(&value))
        cout << "string 값: " << *p << "\n";
    else
        cout << "string 아님\n";

    // 3) 참조로 꺼내서 직접 수정
    any_cast<int&>(value) = 100;
    cout << any_cast<int>(value) << "\n";
}

실행 결과

예외: bad any_cast
int 값: 42
string 아님
100

예외 메시지(what()의 내용)는 컴파일러마다 다를 수 있습니다.

비우기와 제자리 생성

기본 생성한 any는 비어 있습니다. has_value()로 확인하고 reset()으로 다시 비울 수 있습니다. 생성 비용이 큰 객체는 임시 객체를 만들어 대입하는 대신 emplace나 make_any로 생성자 인자를 직접 넘기면 됩니다.

#include <any>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    any value;
    cout << boolalpha << value.has_value() << "\n";   // false

    value = 5;
    cout << value.has_value() << "\n";                 // true

    value.reset();                                     // 비우기
    cout << value.has_value() << "\n";                 // false

    value.emplace<vector<int>>(3, 7);                  // 제자리 생성 : {7, 7, 7}
    cout << any_cast<vector<int>&>(value).size() << "\n";

    auto a = make_any<string>(5, 'x');                 // "xxxxx"
    cout << any_cast<string&>(a) << "\n";
}

실행 결과

false
true
false
3
xxxxx

활용 예제 : 설정 값 저장소

키마다 다른 타입의 값을 저장하는 간단한 설정 클래스입니다. map<string, any>에 값을 담고, 꺼낼 때는 포인터 형태의 any_cast로 타입을 확인한 뒤 맞지 않으면 기본값을 돌려줍니다.

#include <any>
#include <iostream>
#include <map>
#include <string>
using namespace std;

class Settings
{
public:
    template <typename T>
    void Set(const string& key, T value)
    {
        m_values[key] = move(value);
    }

    template <typename T>
    T Get(const string& key, T defaultValue) const
    {
        auto it = m_values.find(key);
        if (it == m_values.end())
            return defaultValue;

        if (const T* p = any_cast<T>(&it->second))
            return *p;
        return defaultValue;            // 타입이 다르면 기본값
    }

private:
    map<string, any> m_values;
};

int main()
{
    Settings settings;
    settings.Set("width", 1920);
    settings.Set("title", string("Viewer"));
    settings.Set("fullscreen", true);

    cout << settings.Get("width", 0) << "\n";
    cout << settings.Get("title", string("none")) << "\n";
    cout << boolalpha << settings.Get("fullscreen", false) << "\n";
    cout << settings.Get("height", 1080) << "\n";      // 없는 키
    cout << settings.Get("width", 0.0) << "\n";        // 타입 불일치(int로 저장)
}

실행 결과

1920
Viewer
true
1080
0

마지막 줄은 width를 int로 저장했는데 double로 꺼내려 했기 때문에 기본값 0이 출력되었습니다. any_cast는 암시적 변환을 해 주지 않고 정확히 같은 타입일 때만 성공합니다.

std::variant와 비교

여러 타입 중 하나를 담는다는 점에서 이전 글에서 다룬 std::variant와 비슷하지만 성격이 다릅니다.

구분std::variantstd::any
담을 수 있는 타입템플릿 인자로 지정한 타입 중 하나복사 가능한 모든 타입
타입 검사 시점컴파일 시간 (std::visit 등)실행 시간 (any_cast)
메모리가장 큰 타입 크기만큼 내부에 저장, 힙 할당 없음작은 객체 외에는 힙 할당 가능
적합한 경우가능한 타입이 정해져 있을 때타입을 미리 알 수 없을 때

가능한 타입 목록을 알고 있다면 variant가 더 빠르고 안전합니다. any는 플러그인이나 범용 저장소처럼 타입을 미리 정할 수 없는 경우에 씁니다.

주의할 점

문자열 리터럴을 그대로 대입하면 string이 아니라 const char*로 저장됩니다. 이 상태에서 any_cast<string>을 하면 실패합니다.

#include <any>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    any a = "text";                        // const char* 로 저장됨
    cout << boolalpha << (a.type() == typeid(const char*)) << "\n";   // true
    cout << (any_cast<string>(&a) == nullptr) << "\n";                 // true : string이 아님

    a = string("text");                    // string으로 저장하려면 명시
    cout << (a.type() == typeid(string)) << "\n";                      // true
}

실행 결과

true
true
true
  • any에는 복사 생성 가능한 타입만 담을 수 있습니다. unique_ptr처럼 이동만 가능한 타입은 담을 수 없으므로 shared_ptr로 감싸는 등의 방법을 써야 합니다.
  • 구현체는 작은 객체를 내부 버퍼에 저장(small object optimization)하지만, 큰 객체는 힙 할당이 일어날 수 있습니다. 성능이 중요한 곳에서 남용하지 않는 것이 좋습니다.
  • 꺼낼 때마다 타입 검사가 필요하므로, 타입을 모른 채로 값을 사용하는 코드가 많아지면 오히려 읽기 어려워집니다. 타입이 정해져 있다면 일반 변수, optional, variant를 먼저 고려합니다.

참고

이상으로 std::any에 대해 간단히 알아보았습니다.