【发布时间】:2013-08-07 14:45:55
【问题描述】:
我有一个带有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 :)
}
我收到的错误是
error: no matching function for call to 'G(A&)'
note: candidate is:
note: template<class T> void G(const std::basic_string<_CharT>&)
现在,我知道我可以将G 定义为结构A 中的朋友,它会起作用,但我的问题是很多已经存在并接收std::basic_string<T> 的stl 函数(例如, operator<< 打印函数,或比较运算符,或许多其他函数。
我真的希望能够像使用std::string 一样使用A。有没有办法做到这一点?
【问题讨论】:
-
问题是需要为
G推导出T,并且它不能那样工作(考虑转换函数)。G<char>(a);会起作用,但我想这不是你想要的。 -
是的,
G((std::string)a)也可以,但两者都不是很有效。我想要比仅仅添加str()成员函数而不是转换运算符更短/更好的东西 -
你最好创建一个 ToString 方法。
-
@NeilKirk - 当然,但这意味着转换运算符在许多情况下是无用的。更糟糕的是,这意味着我根本不能使用转换运算符(即使对于非模板函数),因为有时他必须使用
ToString方法而有时他不会让类的用户感到困惑t. -
return 0; // because otherwise I'll get a lot of comments :)包含它您可能会得到更多。它是多余的,所以我会省略它。