我有一个具有复制构造函数和构造函数的类std::reference_wrapper
:
#include <functional>
#include <iostream>
class Class {
public:
Class() {
std::cout << "Class()" << std::endl;
}
Class(Class const &) {
std::cout << "Class(Class const &)" << std::endl;
}
Class(std::reference_wrapper<Class>) {
std::cout << "Class(std::reference_wrapper<Class>)" << std::endl;
}
Class(std::reference_wrapper<const Class>) {
std::cout << "Class(std::reference_wrapper<const Class>)" << std::endl;
}
};
int main() {
Class a;
Class b = a;
Class c = std::ref(a);
Class d = std::cref(a);
}
正常编译时(g++ --std=c++17 test.cpp
),它可以按要求工作,依次调用四个构造函数:
$ ./a.exe
Class()
Class(Class const &)
Class(std::reference_wrapper<Class>)
Class(std::reference_wrapper<const Class>)
-pedantic
但是,使用(ie, )编译g++ --std=c++17 -pedantic test.cpp
会导致以下错误(以及另一个等效的错误std::cref
):
test.cpp:23:22: error: conversion from 'std::reference_wrapper<Class>' to 'Class' is ambiguous
Class c = std::ref(a);
^
note: candidate: std::reference_wrapper<_Tp>::operator _Tp&() const [with _Tp = Class]
note: candidate: Class::Class(std::reference_wrapper<Class>)
为什么会这样(即,我如何违反标准,在Conversion constructor vs. conversion operator: priority中回答),以及如何在不-pedantic
符合标准的情况下获得结果?
$ g++ --version
g++.exe (Rev1, Built by MSYS2 project) 7.2.0