【问题标题】:C++ - Function template specialization not being calledC++ - 未调用函数模板特化
【发布时间】: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 编译并运行以对其进行测试,但经过测试,我发现未调用专业化。它调用主模板。我不知道为什么。

【问题讨论】:

  • 你不应该专门针对&lt;const char&amp;&gt; 的情况,但是对于&lt;char&gt;,最好根本不专门,并提供非模板函数重载
  • 当我尝试得到一个编译器错误:error: template-id 'validate' for 'bool validate(char, char, char)' does not match any template declaration 不幸的是,因为这是家庭作业,我无法更改 main.cpp 中的代码。我必须使用模板专业化。
  • 如果T=char,则参数应保持const char&amp;
  • 之后代码表现如预期!非常感谢。 :)

标签: c++ function templates character specialization


【解决方案1】:

当来自主模板的类型模板参数T 被推断或明确指定为const char&amp; 时,编译器会选择template &lt;&gt; bool validate&lt;const char&amp;&gt; 特化。对于validate('a', 'b', 'c') 的调用,T 被推断为char,这与专业化所期望的不符。

要么为char 提供一个特化(即不是const char&amp;):

template <>
bool validate<char>(const char& minimum, const char& maximum, const char& testValue)
{
    return validate(toupper(minimum), toupper(maximum), toupper(testValue));
}

或将重载定义为非模板:

bool validate(char minimum, char maximum, char testValue)
{
    return validate(toupper(minimum), toupper(maximum), toupper(testValue));
}

【讨论】:

  • 这非常有用。感谢您向我解释该过程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
相关资源
最近更新 更多