【问题标题】:'Adding Member Function to only Specialized Template of Class'仅将成员函数添加到类的专用模板
【发布时间】:2022-01-06 10:37:55
【问题描述】:

我有一个模板类,我想为模板的特定特化添加一个特殊功能。这个函数只对 std::string 模板有意义。

我展示了我目前是如何处理这个问题的......问题是删除的函数仍然对所有模板类型可见,而不仅仅是我想使用它的 Match 模板。

有没有更优雅的方式来处理这种困境?

 template<typename T> 
 class Match {

  /*
   *Class Definition
   * 
   */

   void string_function() = delete;
 };

template<>
void Match<Std::string>::string_function(){

    //do something that only makes sense with strings
}

【问题讨论】:

    标签: c++ templates c++17 template-specialization


    【解决方案1】:

    您可以将通用代码分解到基类模板中,并使用定制的功能进行派生专业化。

    template <typename T>
    class BaseMatch { /* Common features across all specializations... */ };
    
    template <typename T>
    class Match : BaseMatch<T> { /* Generic case, no custom behavior to enforce */ };
    
    template <>
    class Match<std::string> : BaseMatch<std::string> {
        void string_function() { /* ... */ }
    };
    

    【讨论】:

    • 嘿,非常感谢您的回答。我可以知道您为什么编辑了 SFINAE 解决方案以支持这种派生的专业化解决方案吗?
    • @Blondie sfinae 解决方案无法工作,因为 T 对于给定的专业化是静态的。因此,2 个string_function 之一会发出编译器错误,因为enable_if_t 无效。
    • 哦,好的,非常感谢。这种派生的专业化解决方案非常优雅。
    • 如果我想对外界隐藏 BaseMatch 的定义怎么办?
    • @Blondie 模板编程中的常见做法(因为您无法隐藏实现细节)是将这些细节简单地包含在 namespace detail 中。
    【解决方案2】:
    void string_function() = delete;
    

    它将从类范围中释放函数,再次尝试定义函数。 这就像如果您删除了一个 gmail 帐户并尝试登录说无法登录, 这是不可能的,我可以知道你想删除的原因,而不是想出一些解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      相关资源
      最近更新 更多