我有转换运算符的简单代码,似乎所有编译器都给出了不同的结果,好奇哪个编译器(如果有的话)是正确的? 我尝试了不同的组合,但下面的组合是最有趣的。代码是使用C ++ 11标志编译的,但在C ++ 03中也可以观察到相同的行为。
#include <iostream>
struct call_operator {
template<typename T>
operator T() {
std::cout << __FUNCTION__ << std::endl;
return {};
}
template<typename T>
operator const T&() const {
std::cout << __FUNCTION__ << std::endl;
static T t;
return t;
}
template<typename T>
operator T&() const {
std::cout << __FUNCTION__ << std::endl;
static T t;
return t;
}
};
int main() {
(void)static_cast<int>(call_operator());
(void)static_cast<const int&>(call_operator());
(void)static_cast<int&>(call_operator());
}
铛-3.6:
operator int
operator const int &
operator int &
克++ - 4.9:
operator T
operator const T&
operator T&
msvc 2014 CTP:
call_operator.cpp(17): error C2440: 'static_cast': cannot convert from 'call_operator' to ' const int &'
删除后:
template<typename T>
operator T();
msvc编译:
call_operator::operator const int &
call_operator::operator const int &
call_operator::operator int &
此外,在
中删除const之后template<typename T>
operator const T&();
铛-3.6:
call_operator.cpp:26:9: error: ambiguous conversion for static_cast from 'call_operator' to 'int' (void)static_cast<int>(call_operator());
克++ - 4.9:
operator T
operator const T&
operator T&
msvc 2014 CTP:
call_operator.cpp(16): error C2440: 'static_cast': cannot convert from 'call_operator' to 'int'