Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ ';仅向类的专用模板添加成员函数_C++_Templates_C++17_Template Specialization - Fatal编程技术网

C++ ';仅向类的专用模板添加成员函数

C++ ';仅向类的专用模板添加成员函数,c++,templates,c++17,template-specialization,C++,Templates,C++17,Template Specialization,我有一个模板类,我想向模板的特定专门化添加一个特殊函数。此函数仅适用于std::string模板 我展示了我目前是如何处理这个问题的……问题是,删除的函数对所有模板类型仍然可见,而不仅仅是我想要使用它的匹配模板 有没有更优雅的方法来处理这个难题? template<typename T> class Match { /* *Class Definition * */ void string_function() = delete; }; t

我有一个模板类,我想向模板的特定专门化添加一个特殊函数。此函数仅适用于std::string模板

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

有没有更优雅的方法来处理这个难题?

 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
}
模板
班级比赛{
/*
*类定义
* 
*/
void string_function()=删除;
};
模板
void Match::string_函数(){
//做一些只有字符串才有意义的事情
}

您可以在基类模板中考虑通用代码,并使用定制的功能进行派生专门化

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() { /* ... */ }
};
模板
类BaseMatch{/*跨所有专门化的公共特性…*/};
模板
类匹配:BaseMatch{/*泛型,无需强制的自定义行为*/};
模板
班级比赛:棒球比赛{
空字符串函数(){/*…*/}
};
它将从类作用域中释放函数,再次尝试定义函数。 这就好比你删除了一个gmail帐户,然后尝试登录时说“无法登录”,
这是不可能的,好吧,我可以知道你想删除的原因吗?我可以想出一些解决方案。

嘿,非常感谢你的回答。我能知道你为什么编辑了SFINAE解决方案而支持此派生专门化解决方案吗?@Blondie SFINAE解决方案无法工作,因为对于给定的专门化,T是静态的。因此,2个
string\u函数之一
将发出编译器错误,因为
enable\u if\t
无效。哦,好的,非常感谢。这个派生的专门化解决方案非常优雅。如果我想对外界隐藏BaseMatch的定义,该怎么办?@Blondie在模板编程中的常见做法(因为你不能隐藏实现细节)是将这些细节包含在
名称空间细节中。
void string_function() = delete;