Visual Studio 2013'显式'关键字错误?

 喜欢在他耳边唱歌 发布于 2023-02-11 17:52

考虑以下程序:

#include 

class A
{
public:
  A( ) { std::cout << "A()\n"; }

  A( A& ) = delete;

  A( int i ) { std::cout << "A( " << i << " )\n"; }

  explicit operator int( ) { std::cout << "operator int()\n"; return 42; }
};

template< typename T = A > void f( T a = A() ) {}

int main( void )
{
  f();
  return 0;
}

Visual Studio 2013编译此代码并使用输出运行

A()
operator int()
A( 42 )

这是编译器错误吗?看起来VS编译器在此上下文中没有注意到'explicit'关键字.根据我的理解,VS 2013错误地使用operator int()结合A(int)来排序'copy-construct'A作为f的默认参数.

两者都加了

A a;
A a1( a );

主要和声明f为

void f( A a = A() ) {}

不编译,VS抱怨A(A&)被删除,这似乎是正确的行为.只有在函数模板default参数的上下文中,operator int()和A(int)的组合似乎可以替代A(A&).

g ++ 4.7.3不编译代码并抱怨:

main.cpp: In function ‘int main()’:
main.cpp:21:7: error: no matching function for call to ‘A::A(A)’
main.cpp:21:7: note: candidates are:
main.cpp:10:3: note: A::A(int)
main.cpp:10:3: note:   no known conversion for argument 1 from ‘A’ to ‘int’
main.cpp:6:3: note: A::A()
main.cpp:6:3: note:   candidate expects 0 arguments, 1 provided

删除'explicit'使得g ++编译代码并且输出是相同的.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有