C++ 转换运算符
此代码不可编译。 我在标准中找不到原因。有人能解释一下吗C++ 转换运算符,c++,C++,此代码不可编译。 我在标准中找不到原因。有人能解释一下吗 #include <iostream> #include <string> template<typename T> class S { public: explicit S(const std::string& s_):s(s_) { } std::ostream& print(std::ostream& os) const { os
#include <iostream>
#include <string>
template<typename T>
class S
{
public:
explicit S(const std::string& s_):s(s_)
{
}
std::ostream& print(std::ostream& os) const
{
os << s << std::endl;
return os;
}
private:
std::string s;
};
template<typename T>
std::ostream& operator << (std::ostream& os, const S<T>& obj)
{
return obj.print(os);
}
/*template<>
std::ostream& operator << <std::string> (std::ostream& os, const S<std::string>& obj)
{
return obj.print(os);
}*/
class Test
{
public:
explicit Test(const std::string& s_):s(s_)
{
}
//operator std::string() const { return s; }
operator S<std::string>() const { return S<std::string>(s); }
private:
std::string s;
};
int main()
{
Test t("Hello");
std::cout << t << std::endl;
}
#包括
#包括
样板
S类
{
公众:
显式S(const std::string&S_uu):S(S_u)
{
}
std::ostream&print(std::ostream&os)常数
{
os这是因为除了数组到指针、函数到指针、左值到右值以及顶级常量/易失性删除之外,没有任何转换(参见c++11或c++03,14.8.2.1),在匹配模板函数时被考虑。具体地说,在为运算符推导T
时,不考虑用户定义的转换运算符Test->S
,这是因为除了数组到指针、函数到指针、左值到右值和顶级常量/易失性移除之外,没有任何转换(参见c++11或c++03,14.8.2.1),在匹配模板函数时被考虑。具体来说,在为运算符推导T
时,不考虑用户定义的转换运算符Test->S
。@jpalecek答案的第一段解释了问题所在。如果需要解决方法,可以添加如下声明:
inline std::ostream& operator<< (std::ostream& os, const S<std::string>& s)
{ return operator<< <> (os, s); }
inline std::ostream&operator@jpalecek答案的第一段解释了问题所在。如果需要解决方法,可以添加如下声明:
inline std::ostream& operator<< (std::ostream& os, const S<std::string>& s)
{ return operator<< <> (os, s); }
inline std::ostream&operator但是is\u::value
仍然是假的-这真的会改善什么吗?我不知道is\u\S
会如何神奇地将Test
转换成S
来打印它的内容。你能扩展吗?但是is\u\u::value
仍然是假的-这真的会改善什么吗?我看不出来“howis_
会神奇地将Test
转换为S
以打印其内容。您可以展开吗?”?
template <class T>
struct is_S {
static const bool value = false;
};
template <class T>
struct is_S<S<T>> {
static const bool value = true;
typedef T T_type;
};
template <>
struct is_S<Test> {
static const bool value = true;
typedef string T_type;
};
inline std::ostream& operator<< (std::ostream& os, const S<std::string>& s)
{ return operator<< <> (os, s); }