【问题标题】:c++ templately template specializationc++ 模板化模板特化
【发布时间】:2022-07-05 16:34:50
【问题描述】:

我有一个模板函数,它没有参数

template<typename T>
T cast() {
    return T();
}

我想将它专门用于一些模板类,如矢量,如

template<typename T>
template<>
vector<T> cast<vector<T>>() {
    // something special
    return vector<T>()
}

因为它不带参数,所以它不能被重载。 我应该怎么做才能实现它?

【问题讨论】:

  • 部分专业化功能不是一回事。您可以使用静态函数创建一个类并部分专门化该类,或者选择何时使用 SFINAE 技术操作该函数。

标签: c++ templates specifications


【解决方案1】:

函数不能偏特化。

你可能

  • 提供另一个自定义点

    • 可以部分特化的类:

      template <typename T>
      struct impl
      {
          T operator()() const { return T(); }
      };
      
      template <typename T>
      struct impl<std::vector<T>>
      {
          std::vector<T> operator()() const { /*Something special*/ return std::vector<T>(); }
      };
      
      template<typename T>
      T cast() {
          return impl<T>{}();
      }    
      
    • 转发到带有“标签”的重载函数:

      template <typename T>
      T impl(std::struct_identity<T>)
      {
          return T();
      };
      
      template <typename T>
      std::vector<T> impl(std::struct_identity<std::vector<T>>)
      {
          /*Something special*/
          return std::vector<T>();
      };
      
      template<typename T>
      T cast() {
          return impl(std::struct_identity<T>{});
      }    
      
  • 或从 C++20 开始,您可能会因约束而重载:

    // traits to detect std::vector
    template <typename T>
    struct is_vector : std::false_type {};
    
    template <typename T, typename A>
    struct is_vector<std::vector<T, A>> : std::true_type {};
    
    template<typename T>
    T cast() {
        return T();
    }
    
    template<typename T>
    requires(is_vector<T>)
    T cast() {
        /*Something special*/
        return T();
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多