代码之家  ›  专栏  ›  技术社区  ›  user5534993

如何从typedef组合推导嵌套类模板类型?

  •  1
  • user5534993  · 技术社区  · 4 年前

    我想从 typedef别名 对于一个专门的类模板。使用相同(但未知)的类模板类型并修改包含的类型。

    如何推导别名的类模板类型?

    我尝试使用模板参数 $ clang++ prog.cc -Wall -Wextra -std=c++14 -pedantic :

    // ----------------------
    // third-party header file; may not be modified
    
    template<typename V>
    struct UnknownContainer
    {
        V m;
    };
    
    typedef UnknownContainer<int> KnownAlias;
    
    // ----------------------
    // my file (includes third-party header)
    // only knows KnownAlias, not UnknownContainer
    
    #include <iostream>
    #include <cstdlib>
    #include <type_traits>
    
    template< template <typename> class C >
    using MakeConstValueType = C< const int >;
    
    typedef MakeConstValueType<KnownAlias> MyContainer;
    
    // example usage
    
    void foo(const MyContainer& c)
    {
        std::cout << "value = " << c.m << std::endl;
    }
    
    int main()
    {
        MyContainer c { 42 };
        foo(c);
    }
    

    prog.cc:23:28: error: template argument for template template parameter must be a class template or type alias template
    typedef MakeConstValueType<KnownAlias> MyContainer;
                               ^
    

    有什么想法吗?

    1 回复  |  直到 4 年前
        1
  •  1
  •   StoryTeller - Unslander Monica    4 年前

    总的来说,它可以看起来像这样

    template<class Container, typename NewValT> struct MakeConstValueTypeHelper;
    
    template< template <typename> class C, typename ValueT, typename NewValT>
    struct MakeConstValueTypeHelper<C<ValueT>, NewValT> {
        using type = C<NewValT>;
    };
    
    template< class C >
    using MakeConstValueType = typename MakeConstValueTypeHelper<C, const int>::type;