通过指针函数/const 指针函数进行 C++ 模板部分专业化是否不同?

C++ template partial specialization by a function of pointer / a function of const pointer are not different?

让我们考虑以下代码:

template <typename T>
class Foo
{};

template <typename T, typename U>
class Foo<T(*)(U* const)>
{};

template <typename T, typename U>
class Foo<T(*)(U*)>
{};

当我尝试编译它时 (ideone) 它没有告诉我这两个模板特化是相同的。这是令人惊讶的,因为通常 U*U* const 是不同的东西(第二个是 const 指针)。这里有什么问题?

你必须这样写:

template <typename T, typename U>
class Foo<T(*)(const U* )>
{};

在确定函数的类型(俗称其签名)时,将删除顶级 cv 限定符。

§8.3.5/5 ... The type of a function is determined using the following rules. ... After producing the list of parameter types, any top-level cv-qualifiers modifying a parameter type are deleted when forming the function type. ...

函数指针或模板参数没有特殊规则会使它无效。