【问题标题】:How to deduce template parameter in explicit specialization of function template?如何在函数模板的显式特化中推导出模板参数?
【发布时间】:2016-08-25 23:14:15
【问题描述】:

考虑以下情况:

#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&lt;int&gt;(const int) 而不是 f&lt;const int&gt;(const int)。这里会发生什么?我的第一个想法是顶级const在函数类型转换中被丢弃,所以#2的类型是void(int),这导致f&lt;int&gt;(const int)的特化。但我不确定。

为什么 C++ 允许这样的语法?我的意思是,由于我们不能对函数模板进行部分特化,如果我们想显式地特化一个函数模板,我们就会知道模板参数的值。那么为什么 C++ 不只是强制程序员在特化模板函数时显式地提供模板参数值呢? (即我们必须在template &lt;&gt; void f&lt;int&gt;(const int) { }template &lt;&gt; void f&lt;int const&gt;(const int) { } 中编写#1 的特化)除了编码方便之外,它有什么特殊用途吗?

【问题讨论】:

    标签: c++ template-specialization


    【解决方案1】:
    void f(const int p)
    

    暂且不说模板的问题,这里const部分暂时没有指定f()的参数类型。 const 在这里指定的所有内容是p 在函数f() 中是constf()的参数类型为int

    template <> void f(const int)
    

    当编译器试图推断特化的类型时,它推断由于函数参数的类型是int,这一定是f&lt;int&gt;的特化。

    真的不能以这种方式进行扣除。如果你想这样做,你必须明确:

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

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 2013-11-04
      • 2018-12-05
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多