c++ - 显式实例化

标签 c++ templates explicit-specialization

这是由 this 激发的文章(第5页)

template<class T> 
T const &f(T const &a, T const &b){
    return (a > b ? a : b);
}

template int const &f<int>(int const &, int const &);

int main(){
    int x = 0, y = 0;
    short s = 0;
    f(x, y);     // OK
    f(x, s);     // Is this call well-formed?
}

是调用'f(x, s)'良构?我假设因为函数模板 'f'被显式实例化,将应用标准转换,因此 'short s'将转换为 'int'匹配对显式特化的调用 'f<int>' .但这似乎是错误的?

标准的哪一部分讨论了这种情况下的适用规则?

最佳答案

不,调用 f(x, s) 格式不正确。由于您没有明确说明要使用的特化,因此编译器使用参数推导来尝试实例化函数模板;这失败了,因为 xs 有不同的类型,所以 T 是不明确的。

适用的规则在13.3.1的重载解析过程的规范中:

In each case where a candidate is a function template, candidate function template specializations are generated using template argument deduction (14.8.3, 14.8.2). Those candidates are then handled as candidate functions in the usual way.

14.8.3/1 也是相关的:

For each function template, if the argument deduction and checking succeeds, the template arguments (deduced and/or explicit) are used to instantiate a single function template specialization which is added to the candidate functions set to be used in overload resolution. If, for a given function template, argument deduction fails, no such function is added to the set of candidate functions for that template.

函数模板被显式实例化为T = int,但编译器不知道它应该使用这个实例化,直到它执行模板参数推导以确定什么T 应该是。

关于c++ - 显式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3723630/

相关文章:

iphone - 我在哪里可以找到 iPhone 上 opencv 的 xcode 模板?

c++ - "expected initializer before ' < ' token"尝试模板成员特化

c++ - 在 C++14 中使用自动返回 'type' 进行显式模板特化是否有效?

c++ - 嵌套的 Switch 语句 - 返回到 switch 的开头

c++ - 数组初始化

c++ - 如何在 Switch 语句中使用 Cmd 行参数中提供的 TCHAR*?

c++ - 模板偏特化问题

c++ - 计算 ICMP 数据包校验和

c++ - 如何将参数转发给模板成员函数到 C++ 中的成员基类指针

c++ - 根据派生类型选择类的显式特化