具有模板函数的转换运算符
conversion operator with template functions
我有一个类,它带有到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
。有办法做到这一点吗?
我真的希望能够像使用
std::string
一样使用A。有办法做到这一点吗?
是的,但你确定你真的想要这个吗?解决方案是:
struct A : public std::string {
};
但请记住,std::string
没有virtual
析构函数,因此不能多晶型使用你已经被警告了
str()
是一个更好的解决方案,当您想将A
传递给采用std::basic_string<T>
的函数时,它允许您显式。
编译器不能推断出那么远;您要么必须显式调用强制转换运算符,要么显式指定模板参数:
G(static_cast<std::string>(a));
G<char>(a);
为了理解为什么编译器不能同时进行用户定义的转换和模板参数推导,让我们举一个例子:
template<typename T>
struct Number {
Number(double n) {};
Number(int n) {};
};
struct A{
operator Number<double>(){return Number<double>(1.);}
operator Number<int>(){return Number<int>(1);}
};
template<typename T> void G(Number<T>& number) { }
int main(){
A a;
G(a); // What do I do ?!
return 0;
}
在这种情况下编译器应该怎么做?
G
的明确专业化将起作用。
G<char>(a);
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 构造函数和转换运算符之间的重载解析
- 分配给转换运算符失败-C++
- 转换运算符不适用于sleep_until
- 继承模板化转换运算符
- 模板转换运算符在 clang 6 和 clang 7 之间的区别
- 如何在模板化转换运算符中消除此构造的歧义?
- 为什么选择转换运算符的重载?
- 如何避免强制转换运算符 () 和访问运算符 [] 冲突?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 了解转换运算符的选择C++
- 多个隐式转换运算符
- 这个typedef和转换运算符语法是什么意思
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 类模板忽略了用户定义的转换运算符(非模板不忽略)
- 为什么在std::for_each()返回时调用转换运算符
- 为什么 std::optional 的强制转换运算符被忽略了
- 使用用户定义的转换运算符推导函数模板参数
- 模板转换运算符的分辨率不明确
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?