C++ 类型检查模板类参数
我试图通过禁止诸如string->bool之类的隐式类型转换来实现模板类参数的类型检查,从而引发编译错误。 具体的场景很简单,如下所示:C++ 类型检查模板类参数,c++,templates,typechecking,C++,Templates,Typechecking,我试图通过禁止诸如string->bool之类的隐式类型转换来实现模板类参数的类型检查,从而引发编译错误。 具体的场景很简单,如下所示: #include <iostream> #include <string> using namespace std; template <class T> class myPair { T a, b; public: myPair(T first, T second ) { a = first; b = sec
#include <iostream>
#include <string>
using namespace std;
template <class T>
class myPair {
T a, b;
public:
myPair(T first, T second ) {
a = first;
b = second;
}
void test();
};
typedef myPair<bool> boolParm;
template<class T>
void myPair<T>::test() {
if(a == true) {
cout << "a is true" << endl;
} else {
cout << "a is false" << endl;
}
if(b == true) {
cout << "b is true" << endl;
} else {
cout << "b is false" << endl;
}
}
int main() {
boolParm myObj(false, "false");
myObj.test();
return 0;
}
#包括
#包括
使用名称空间std;
模板
类myPair{
Tα,b;
公众:
myPair(T第一,T第二){
a=第一;
b=秒;
}
无效试验();
};
typedef myPair boolParm;
模板
void myPair::test(){
如果(a==true){
cout乍一看,这的确是一种奇怪的行为;但就我所能说的而言,你不能禁止这种行为——不管怎样,对于像bool
这样的原始类型,你也不能禁止
参数的隐式转换发生在您对它有发言权之前,似乎存在从char const*
到bool
的隐式原语类型转换
另请参见另一个问题:一个解决方法是添加模板化工厂函数以创建myPair
template <typename T>
myPair<T> makeParam(T a, T b) {
return myPair<T>(a, b);
}
或者更改构造函数:
template <typename U, typename V>
myPair(U a, V b);
模板
myPair(U a,V b);
并根据需要专门化
这种专门化的一个例子:
template <class T>
class myPair {
T a, b;
public:
template <typename U, typename V> // generic version
myPair(U first, V second)
{
// intentionally fail to compile
static_assert(false, "don't support generic types");
}
template <> // template specialization
myPair(T first, T second)
{
// explicitly require exactly type T
a = first;
b = second;
}
};
模板
类myPair{
Tα,b;
公众:
模板//通用版本
myPair(U第一,V第二)
{
//故意不编译
静态_断言(false,“不支持泛型类型”);
}
模板//模板专门化
myPair(T第一,T第二)
{
//显式要求完全是类型T
a=第一;
b=秒;
}
};
Ah因为这里是模板解析失败,而不是参数转换!巧妙!感谢评论…我的问题是main()中的部分是用户代码,我不能要求用户更改其代码或支持以上格式的已编写的用户代码。我只能在基类(即myPair)中进行修改以实现此功能。@gigaplex:您能否像第二部分中提到的那样,再详细介绍一下如何在此场景中使用专门化选项!我已经在我的answer@gigaplex:感谢您提供的示例。但是我对如何使用模板专门化有点困惑。例如,以下代码无法编译:[CODE]模板类myPair{T a,b;public:myPair(T first,T second);};typedef myPair boolParm;template myPair::myPair(T first,T second){a=first;b=second;}template myPair::myPair(T first,T1 second){static_assert(false,“不支持泛型类型”);}[/CODE]
template <class T>
class myPair {
T a, b;
public:
template <typename U, typename V> // generic version
myPair(U first, V second)
{
// intentionally fail to compile
static_assert(false, "don't support generic types");
}
template <> // template specialization
myPair(T first, T second)
{
// explicitly require exactly type T
a = first;
b = second;
}
};