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

将类模板作为模板参数传递

  •  0
  • Timo  · 技术社区  · 5 年前

    是否可以传递类模板(如 std::vector ,而不是像 std::vector<int> )作为模板参数?我想编写一个类型来检查给定类型是否是给定模板的实例。我知道编译器不允许传递未实例化的模板,但是我想知道是否有比我得到的更好的解决方法。

    我的实现(注意我删除 TArgs 在最底层):

    #include <type_traits>
    
    template <typename Instance, typename Template>
    struct IsInstanceOf : std::false_type {};
    
    template <
          template <typename...> typename Instance,
          template <typename...> typename Template, 
          typename... IArgs,
          typename... TArgs>
    struct IsInstanceOf<Instance<IArgs...>, Template<TArgs...>>
        : std::is_same<Instance<IArgs...>, Template<IArgs...>> {};
    

    这个实现是可行的,但是我必须用某种类型的模板进行实例化,例如:

    IsInstanceOf<std::vector<float>, std::vector<void>>::value
    

    这种行为是意料之中的,但我想知道是否还有更好的,比如

    IsInstanceOf<std::vector<float>, std::vector<>>::value 
    // since this is illegal
    IsInstanceOf<std::vector<float>, std::vector>::value
    

    Here 是指向示例的链接。

    1 回复  |  直到 5 年前
        1
  •  4
  •   Nikita Kniazev    5 年前
    #include <type_traits>
    
    template <typename T, template <typename...> typename Template>
    struct IsInstanceOf : std::false_type {};
    
    template <
          template <typename...> typename Template,
          typename... TArgs>
    struct IsInstanceOf<Template<TArgs...>, Template>
        : std::true_type {};
    
    #include <vector>
    static_assert(IsInstanceOf<std::vector<float>, std::vector>::value);
    static_assert(!IsInstanceOf<int, std::vector>::value);
    #include <string>
    static_assert(!IsInstanceOf<std::string, std::vector>::value);
    static_assert(IsInstanceOf<std::string, std::basic_string>::value);
    
    int main() {}
    

    https://wandbox.org/permlink/PTXl0KoxoJ2aFJfK