【问题标题】:what is the type of decltype(function) and why I do not need "const" qualifier here?decltype(function) 的类型是什么,为什么我在这里不需要“const”限定符?
【发布时间】:2019-12-02 20:56:21
【问题描述】:

我对 decltype 函数的类型感到困惑。它既不是函数指针也不是函子。我该如何使用它?以及为什么这里的完整模板专业化不需要const 限定符。

class SomeClass
{
public:
    template <typename T>
    void insideTemplateMethod(const T & value)
    {
    }
};
template
void SomeClass::insideTemplateMethod<decltype(std::hex)>(decltype(std::hex) & ); // no need to specify const

template
void SomeClass::insideTemplateMethod<int>(int &); // error, must specify const

int main(void)
{}

如果我删除 &amp;,它会抱怨

error: template-id 'insideTemplateMethod<std::ios_base&(std::ios_base&)>' for 'void SomeClass::insideTemplateMethod(std::ios_base& (*)(std::ios_base&))' does not match any template declaration"

你看,参数字段中的decltype(std::hex)被扣除为std::ios_base&amp; (*)(std::ios_base&amp;),而模板的参数中被扣除为std::ios_base&amp;(std::ios_base&amp;)

你能帮我理解一下吗?

【问题讨论】:

  • 函数是不可变的,因此函数指针的 const 是多余的。

标签: c++ templates metaprogramming template-specialization explicit-specialization


【解决方案1】:

std::hex 是一个函数,具有以下声明(参见cppreference):

std::ios_base& hex( std::ios_base& str );

如果T是这个函数的类型,即std::ios_base&amp;(std::ios_base&amp;),那么因为是函数类型,所以const TT是一样的。这就是为什么可以在没有const 的情况下编写显式实例化定义的原因。

请注意,如果您从显式实例化定义中删除&amp;,则函数参数类型decltype(std::hex) 会经历从函数类型到函数指针类型的标准转换。这就是您在错误消息中看到(*) 的原因。

【讨论】:

  • 只是为了澄清 OP:没有 &,函数类型“衰减”。这是 C++ 的标准过程,其中数组衰减为指针,函数衰减为函数指针。
【解决方案2】:

引用the standard

cv-qualifier-seq 在函数声明器中的效果与在函数类型之上添加 cv-qualification 不同。在后一种情况下,cv-qualifiers 被忽略。 [ 注意:具有 cv-qualifier-seq 的函数类型不是 cv-qualified 类型;没有 cv 限定 函数类型。 ——尾注] [ 例子:

typedef void F();
struct S {
    const F f;        // OK: equivalent to: void f();
};

——结束示例 ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多