I have a simple issue with ctor overload resolution for a class template:
#include <iostream>
#include <string>
using namespace std;
enum EnumTypeVal { READ, WRITE };
template <class T>
class TemplateClassTest {
public:
TemplateClassTest(const string & stringVal, T typeVal, EnumTypeVal e = READ,
const string & defaultStringVal = "default");
TemplateClassTest(const string & stringVal, const char * charVal);
TemplateClassTest(const string & stringVal, EnumTypeVal e = READ,
const string & defaultStringVal = "default");
private:
T type;
};
template <class T>
TemplateClassTest<T>::TemplateClassTest(const string & stringVal, T typeVal,
EnumTypeVal e,
const string & defaultStringVal)
{
type = typeVal;
cout << "In TemplateClassTest(const string &, T, EnumTypeVal, "
"const string &)" << endl;
}
template <class T>
TemplateClassTest<T>::TemplateClassTest(const string & stringVal,
const char * charVal)
{
cout << "In TemplateClassTest(const string &, const char *)" << endl;
}
template <class T>
TemplateClassTest<T>::TemplateClassTest(const string & stringVal, EnumTypeVal e,
const string & defaultStringVal)
{
cout << "In TemplateClassTest(const string &, EnumTypeVal, const string &)"
<< endl;
}
typedef TemplateClassTest<long long unsigned int> u32Type;
typedef TemplateClassTest<bool> boolType;
int main()
{
u32Type l("test", "0"); //matches ctor 2
u32Type v("test", 0); // ambiguity between ctor 1 and 2
boolType b("test", "true"); //matches ctor 2
return 0;
}
The second call fails to compile by throwing error:
Call of overloaded 'TemplateClassTest(const char [5], int) is ambiguous.
Why does int
matches to const char *
? This situation can be solved by changing the const char *
to const string &
in ctor 2. But doing so, boolType b("test", "true")
now gets matched to ctor 1 instead of ctor 2.
My requirements are:
u32Type v("test", 0)
should match ctor 1boolType b("test", "true")
should match ctor 2.
Limitations are:
- ctor 1 and 3 signatures can't be changed
- user code calls in main() can't be changed.
Any help is highly appreciated..Thanks!
typedef TemplateClassTest<int> u32Type;
would solve the problem, as ctor 1 becomes an Exact Match. I'm not sure if that wouldn't break something different, asint
is not required to have exactly 32 bits. – dypnullptr
keyword. – Manu343726template<>
for the explicitly specialized class template. Just useTemplateClassTest<bool>::TemplateClassTest(const string&, const char*) { /*..*/ }
– dyp