超載分辨率低於失敗clang35 -std=c++11
編譯:列表初始化和失敗的initializer_list構造
#include <iostream>
#include <string>
#include <initializer_list>
class A
{
public:
A(int, bool) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
A(int, double) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
A(std::initializer_list<int>) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
int main()
{
A a1 = {1, 1.0};
return 0;
}
錯誤
init.cpp:15:14: error: type 'double' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing]
A a1 = {1, 1.0};
^~~
init.cpp:15:14: note: insert an explicit cast to silence this issue
A a1 = {1, 1.0};
^~~
static_cast<int>()
OTOH,它告誡,縮小並編譯g++48 -std=c++11
init.cpp: In function ‘int main()’:
init.cpp:15:17: warning: narrowing conversion of ‘1.0e+0’ from ‘double’ to ‘int’ inside { } [-Wnarrowing]
A a1 = {1, 1.0};
^
init.cpp:15:17: warning: narrowing conversion of ‘1.0e+0’ from ‘double’ to ‘int’ inside { } [-Wnarrowing]
和產生的結果
A::A(std::initializer_list<int>)
這兩種行爲都有意義嗎?從cppreference
All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_list
If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all)
引述由於收縮轉換是不允許的,我希望重載解析步驟不匹配A(std::initializer_list<int>)
構造,而是匹配A(int, double)
之一。例如,改變A(std::initializer_list<int>)
到A(std::initializer_list<std::string>)
既clang35
和g++48
並打印
A::A(int, double)
如預期編譯。
大概你的意思是鏗鏘3.5。你命名這個二進制文件並不是真正有用的:)'mv clang25 clang35'「oops」 – 2015-02-07 04:39:39
你是對的:)這是團隊在工作中維護構建系統時使用的版本控制慣例,我從來沒有給過它一個想法。 – Pradhan 2015-02-07 07:00:43