【发布时间】:2013-11-05 18:45:08
【问题描述】:
我有一个关于类模板的 ctor 重载解析的简单问题:
#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;
}
第二次调用编译失败,抛出错误:
重载 'TemplateClassTest(const char [5], int) 的调用不明确。
为什么int 与const char * 匹配?这种情况可以通过将 ctor 2 中的 const char * 更改为 const string & 来解决。但是这样做,boolType b("test", "true") 现在会匹配到 ctor 1 而不是 ctor 2。
我的要求是:
-
u32Type v("test", 0)应该匹配 ctor 1 -
boolType b("test", "true")应该匹配 ctor 2。
限制是:
- ctor 1 和 3 签名无法更改
- main() 中的用户代码调用无法更改。
任何帮助都非常感谢..谢谢!
【问题讨论】:
-
只保留模板构造函数,将其特化为 T=char const*
-
typedef TemplateClassTest<int> u32Type;将解决问题,因为 ctor 1 成为精确匹配。我不确定这是否会破坏一些不同的东西,因为int不需要正好有 32 位。 -
这是为什么 C++11 添加了
nullptr关键字的完美示例。 -
@DyP:假设我已经有另一个 typedef TemplateClassTest
intType; -
@CodeWarrior 1) ctor 是私有的。 2) 显式特化类模板的成员函数的外联定义不包含显式特化类模板的
template<>。只需使用TemplateClassTest<bool>::TemplateClassTest(const string&, const char*) { /*..*/ }
标签: c++ templates constructor overload-resolution constructor-overloading