Ada*_*dam 6 c++ templates template-specialization c++17
我有一个模板类,我想向模板的特定专业化添加特殊函数。此函数仅对 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
}
Run Code Online (Sandbox Code Playgroud)
您可以将公共代码分解到基类模板中,并使用定制的功能进行派生专业化。
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() { /* ... */ }
};
Run Code Online (Sandbox Code Playgroud)