【发布时间】:2012-10-14 10:06:58
【问题描述】:
作为对another question的回复,我想贴出如下代码(也就是我想贴出基于这个想法的代码):
#include <iostream>
#include <utility> // std::is_same, std::enable_if
using namespace std;
template< class Type >
struct Boxed
{
Type value;
template< class Arg >
Boxed(
Arg const& v,
typename enable_if< is_same< Type, Arg >::value, Arg >::type* = 0
)
: value( v )
{
wcout << "Generic!" << endl;
}
Boxed( Type&& v ): value( move( v ) )
{
wcout << "Rvalue!" << endl;
}
};
void function( Boxed< int > v ) {}
int main()
{
int i = 5;
function( i ); //<- this is acceptable
char c = 'a';
function( c ); //<- I would NOT like this to compile
}
然而,虽然 MSVC 11.0 在最后一次调用中阻塞,正如 IHMO 应该的那样,MinGW g++ 4.7.1 只是接受它,并使用右值引用形式参数调用构造函数。
在我看来,它看起来就好像一个左值绑定到一个右值引用。一个灵活的答案可能是将左值转换为右值。但问题是,这是否是编译器错误,如果不是,神圣标准如何允许这样做?
编辑:我设法将其简化为以下非常简短的示例:
void foo( double&& ) {}
int main()
{
char ch = '!';
foo( ch );
}
用 MSVC 11.0 编译失败,用 MinGW 4.7.1 编译,对吗?
【问题讨论】:
-
难道没有从
char到int的隐式转换(来自 C 我希望这样)? -
@H2CO3:在 C++ 中,您可以重载
int与char作为参数类型。所以,不,在这种情况下没有转换。或者,我看不到如何(正确)调用它。 -
@Cheersandhth.-Alf:你可以超载,但你仍然有自动投射。 IE。如果你有
void function(char c) {},它会被收集,但是你从int &&构造Boxed<int>,你从char构造它(合法,因为它是r值,但如果你需要l值,它就不会)。 -
无论如何,我无法想象为什么这个问题会被否决...
-
@H2CO3:我后面跟着一些连续投票者。他或她将其限制在足够低的频率,以至于它不会被 SO 机制自动修复。偶尔的连续投票者在一定程度上弥补了这一点。 :-)
标签: c++ compiler-errors