在 C++ 中专门化一个函数模板?
Specialize a function template in c++?
我必须创建一个通用函数来在 C++ 中对字符串进行排序,并且我必须使用我自己的字符串 class(我已将其实现为 SuchString
)对其进行测试。
我有这样的模板:
template<typename T, class Sel>
void stringSort(T& lel);
Sel
class 包含一个谓词函数来确定排序依据。
我想专门化排序功能,这样它可以和我自己的功能一起正常工作SuchString
class:
template<>
void stringSort<SuchString&>(SuchString& string);
当我这样做时,出现错误:
No function template matches function template specialization 'stringSort
'
专门化这样一个函数的正确方法是什么?我不能简单地重载该函数,因为我需要 Sel
class 包含谓词函数。我不能将此函数作为简单的指针参数传递
到函数,因为任务是使用模板。
感谢任何帮助。
您的原始模板函数包含两种类型:
template<typename T, class Sel>
void stringSort(T& lel);
您正在尝试仅使用 一个 类型来专门化它。因此错误。我不太明白你在这里是如何使用 Sel
的。我假设您真的打算将其作为参数传递:
template<typename T, typename Sel>
void stringSort(T& lel, Sel predicate);
在这种情况下,更简单的做法是为 SuchString
:
提供重载
template <typename Sel>
void stringSort(SuchString&, Sel );
重载优先于模板。
如果您确实需要 Sel
上的静态方法,那么您只需简单地切换模板类型的顺序即可:
template <typename Sel, typename T>
void stringSort(T& );
template <typename Sel>
void stringSort(SuchString& );
这样,如果 foo
是类型 SuchString
的左值,stringSort<SomeSel>(foo)
将调用 SuchString&
重载,否则将调用 T&
版本。
我必须创建一个通用函数来在 C++ 中对字符串进行排序,并且我必须使用我自己的字符串 class(我已将其实现为 SuchString
)对其进行测试。
我有这样的模板:
template<typename T, class Sel>
void stringSort(T& lel);
Sel
class 包含一个谓词函数来确定排序依据。
我想专门化排序功能,这样它可以和我自己的功能一起正常工作SuchString
class:
template<>
void stringSort<SuchString&>(SuchString& string);
当我这样做时,出现错误:
No function template matches function template specialization '
stringSort
'
专门化这样一个函数的正确方法是什么?我不能简单地重载该函数,因为我需要 Sel
class 包含谓词函数。我不能将此函数作为简单的指针参数传递
到函数,因为任务是使用模板。
感谢任何帮助。
您的原始模板函数包含两种类型:
template<typename T, class Sel>
void stringSort(T& lel);
您正在尝试仅使用 一个 类型来专门化它。因此错误。我不太明白你在这里是如何使用 Sel
的。我假设您真的打算将其作为参数传递:
template<typename T, typename Sel>
void stringSort(T& lel, Sel predicate);
在这种情况下,更简单的做法是为 SuchString
:
template <typename Sel>
void stringSort(SuchString&, Sel );
重载优先于模板。
如果您确实需要 Sel
上的静态方法,那么您只需简单地切换模板类型的顺序即可:
template <typename Sel, typename T>
void stringSort(T& );
template <typename Sel>
void stringSort(SuchString& );
这样,如果 foo
是类型 SuchString
的左值,stringSort<SomeSel>(foo)
将调用 SuchString&
重载,否则将调用 T&
版本。