在模板函数和const quailifier中键入deduction [英] Type deduction in templated functions and const quailifier
问题描述
我有以下的c ++ 11代码:
I have the following piece of c++11-code:
#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&
类型,我们有一个 P&& code>作为
函数 f
中的参数我希望模板参数解析为 object&
c $ c>& &&& =& f
应成为
When running I get talk const
which is what it should be, but I'm wondering how it works. From what I read so far the const
-qualifier is ignored in template deduction. Since obj
is of type const object&
and we have a P&&
as parameter in f
I would expect that the template parameter resolves to object&
and since & && = &
the function f
should become
void f(object& p) { makeItTalk(std::forward<object&>(p)); }
但是这个函数甚至不能被调用 obj
。所以我想知道我是否错了,说
const
被忽略了?
But this function is not even allowed to be called for obj
. So I'm wondering if I am wrong by saying the const
is ignored?
推荐答案
根据我的理解,当函数模板接受指针或引用参数时,类型推导不会忽略const限定符。
As I understand it, type deduction does not ignore the const qualifier when the function template takes a pointer or reference parameter. The top-level consts are removed but not the constness of what is pointed to or referenced.
可以在这里找到一个更广泛的参数: http://cpp-next.com/archive/2011/04/appearing -and-disappearing-consts-in-c /
A more extensive argument can be found here: http://cpp-next.com/archive/2011/04/appearing-and-disappearing-consts-in-c/
这篇关于在模板函数和const quailifier中键入deduction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!