我有一个将转换为的类std::string。除了接收函数std::basic_string<T>(在上模板化T)外,它适用于所有事物。
#include <string>
struct A{
operator std::string(){return std::string();}
};
void F(const std::basic_string<char> &){}
template<typename T> void G(const std::basic_string<T> &) {}
int main(){
A a;
F(a); // Works!
G(a); // Error!
return 0; // because otherwise I'll get a lot of comments :)
}
Run Code Online (Sandbox Code Playgroud)
我收到的错误是
error: no matching function for call to 'G(A&)'
note: candidate is:
note: template<class T> void G(const std::basic_string<_CharT>&)
Run Code Online (Sandbox Code Playgroud)
现在,我知道可以G在struct中定义为好友A并且可以使用,但是我的问题是很多已经存在并接收到的stl函数std::basic_string<T>(例如,operator<<打印函数,比较运算符或许多其他函数) 。
我真的很想能够A像它一样使用std::string。有什么办法吗?
我真的很希望能够像使用 A 一样使用它
std::string。有什么办法可以做到这一点吗?
是的,但是你确定你真的想要这个吗?解决办法是:
struct A : public std::string {
};
Run Code Online (Sandbox Code Playgroud)
但请记住,它std::string没有virtual析构函数,因此不能多态使用。你被警告了!!!
Astr()是一个更好的解决方案,当您想要将您的A值传递给采用std::basic_string<T>.
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |