【问题标题】:Type deduction in templated functions and const quailifier模板化函数和 const 限定符中的类型推导
【发布时间】:2013-06-27 10:34:12
【问题描述】:

我有以下一段 c++11 代码:

#include <iostream>

struct object {
    void talk(const char* text) const { std::cout << "talk " << text << std::endl; }
};

void makeItTalk(object& obj) { obj.talk("non-const"); }
void makeItTalk(const object& obj) { obj.talk("const"); }

template<typename P> void f(P&& p) { 
    makeItTalk(std::forward<P>(p));
}


int main() {

    const object obj;
    f(obj);

    return 0;
}

运行时我得到talk const,这是应该的,但我想知道它是如何工作的。从我目前阅读的内容来看,const-qualifier 在模板推导中被忽略。由于obj 是const object&amp; 类型,并且我们在f 中有一个P&amp;&amp; 作为参数,我希望模板参数解析为object&amp;,并且由于&amp; &amp;&amp; = &amp; 函数f 应该成为

void f(object& p) { makeItTalk(std::forward<object&>(p)); }

但是这个函数甚至不允许为obj调用。所以我想知道我说const 被忽略了是不是错了?

【问题讨论】:

  • 我不确定我是否完全理解您的要求,但据我所知,转发常量是std::forward 的预期效果。

标签: c++ templates type-deduction


【解决方案1】:

据我了解,当函数模板采用指针或引用参数时,类型推导不会忽略 const 限定符。顶级 const 被删除,但没有被指向或引用的 const 性。

可以在此处找到更广泛的论点:http://cpp-next.com/archive/2011/04/appearing-and-disappearing-consts-in-c/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多