【发布时间】:2016-11-12 22:04:58
【问题描述】:
这是我的 A 类的定义并为它创建函数:
template< typename T >
class A
{
public:
A( T test )
: _test( test )
{}
public:
const T _test;
};
template <typename T>
A<T> make_a (T&& elem) {
return A<T>{std::forward<T>(elem)};
}
当我将 int lvalue 传递给make_a 函数时,我希望实例化的类类似于
class B
{
public:
B( int &test )
: _test( test )
{}
public:
const int &_test;
};
但是A::_test的类型推导出为int&而不是const int&:
int main(int argc, const char * argv[]) {
int a = 1;
auto aa = make_a(a);
aa._test = 2; // compiled OK
B bb(a);
bb._test = 2; // compilation error
return 0;
}
谁能解释一下导致这种行为的原因?
我正在使用 XCode 7.0、LLVM 7.0 默认编译器。
谢谢。
【问题讨论】:
-
因为
const add_lvalue_reference_t<int>是int&。 -
在
const int&中,int是常量,而不是引用。这是对const int的引用,而不是“对int的常量引用”。但在cons T中,T是const,而不是T的某个子类型。当T是引用类型时,const T表示“常量引用”——但这是一个空操作;从某种意义上说,引用总是const(一旦初始化,您就无法更改它所指的内容)。 -
另一种看待它的方式:如果
T是int*,const T将是int* const(指向非 constint的 const 指针),这根本不是与const int*akaint const*相同(指向 constint的非常量指针)。 -
@IgorTandetnik 答案应该张贴在下面的大文本区域!! :-)
标签: c++ templates perfect-forwarding type-deduction