2016-08-25 66 views
6

考虑以下情况:如何在函数模板的显式特化中推导出模板参数?

#include <iostream> 

template <class T> void f(T) { std::cout << "#1\n"; } // #1 
template <> void f(const int) { std::cout << "#2\n"; } // #2 

int main() { 
    f<const int>(1); // call #1 
    f<int>(1);  // call #2 
    return 0; 
} 

似乎#2是f<int>(const int),而不是f<const int>(const int)。这里发生了什么?我的第一个想法是顶级const在函数类型转换中被丢弃,所以#2的类型是void(int),这导致了f<int>(const int)的专门化。但我不确定这一点。

为什么C++允许这样的语法?我的意思是,既然我们不能部分专门化函数模板,如果我们想明确地专门化一个模板参数值,我们就会知道模板参数的值。那么为什么C++不只是强制程序员在专门化模板函数时明确提供模板参数值呢? (即我们必须在template <> void f<int>(const int) { }template <> void f<int const>(const int) { }中编写#1专业化)除了编码方便之外,它有特殊的用法吗?

回答

6
void f(const int p) 

撇开模板的问题,就目前而言,在const部分在这里不指定参数的类型f()。这里指定const的全部是pconst内部的函数f()f()的参数类型为int

template <> void f(const int) 

当编译器试图推导出的特殊类型,它推断,因为函数参数的类型是int,这必须是f<int>专业化。

这样不能真正扣扣工作。你必须明确,如果这是你想要做的:

template <> void f<const int>(const int) { std::cout << "#2\n"; } 
相关问题