我有一个模板类,我想为模板的特定特化添加一个特殊功能。此函数仅对 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
}
最佳答案
您可以将通用代码分解到基类模板中,并使用定制的功能进行派生特化。
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() { /* ... */ }
};
关于c++ - '仅将成员函数添加到类的专用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51655502/