【发布时间】:2015-08-14 12:54:29
【问题描述】:
我有以下代码:
template<typename T>
bool validate(const T& minimum, const T& maximum, const T& testValue)
{
return testValue >= minimum && testValue <= maximum;
}
template<>
bool validate<const char&>(const char& minimum, const char& maximum, const char& testValue)
{
// Allows comparisons with char arguments, ignoring case
// Localize by calling previously defined function
return validate(toupper(minimum), toupper(maximum), toupper(testValue));
}
第一个模板用于任何输入类型,专门用于文字字符。该代码使用 main.cpp 编译并运行以对其进行测试,但经过测试,我发现未调用专业化。它调用主模板。我不知道为什么。
【问题讨论】:
-
你不应该专门针对
<const char&>的情况,但是对于<char>,最好根本不专门,并提供非模板函数重载 -
当我尝试得到一个编译器错误:error: template-id 'validate
' for 'bool validate(char, char, char)' does not match any template declaration 不幸的是,因为这是家庭作业,我无法更改 main.cpp 中的代码。我必须使用模板专业化。 -
如果
T=char,则参数应保持const char& -
之后代码表现如预期!非常感谢。 :)
标签: c++ function templates character specialization