With the following code, if I attempt to convert a template array to std::string, instead of the compiler using the expected std::string conversion method, it raises an ambiguity resolution problem (as it attempts to call the array conversion methods):
#include <iostream>
template<typename TemplateItem>
class TestA
{
public:
TemplateItem Array[10];
operator const TemplateItem *() const {return Array;}
operator const std::string() const;
};
template<>
TestA<char>::operator const std::string() const
{
std::string Temp("");
return Temp;
}
int main()
{
TestA<char> Test2;
std::string Temp("Empty");
Temp = Test2; //Ambiguity error. std::string or TemplateItem * ?
return 0;
}
What modification do I need to make to the code in order to make it so the code correctly and implicitly resolve to the std::string conversion function? Especially given the const TemplateItem * would be treated as a null-terminated array (which it won’t likely be).
First, the reason you have ambiguity: you provide both conversion to
char*and conversion tostd::string const, andstd::stringlikes them both.By the way, before getting to your question, the
constinoperator std::string constwas once a good idea, advocated by e.g. Scott Meyers, but is nowadays ungood: it prevents efficient moving.Anyway, re the question, just avoid implicit conversions. Make those conversions explicit. Now I answered that in response to another SO question, and someone (I believe the person was trolling) commented that C++98 doesn’t support
explicittype conversion operators. Which was true enough, technically, but pretty stupid as a technical comment. Because you don’t need to use theexplicitkeyword (supported by C++11), and indeed that’s not a good way to make the conversions explicit. Instead just name those conversions: use named member functions, not conversion operators.Cheers & hth.