假设我有一个模板类定义为:
template < typename A, typename B >
class something { ... }
如何测试A型和B型是否属于同一类型?我知道这可以在运行时使用typeid完成,但我真的需要这个是编译时测试。
另外,如果类型A和B相等,我该如何专门化类?
在现实世界中,A将是某种类型的stl容器,例如std :: string,而B将是char或wchar_t。在内部我已经检查了容器value_type(如果不是预期的话,编译错误)。如果B与容器value_type相同,则类中的大多数代码将变为冗余。
答案 0 :(得分:6)
另外,如果类型A和B相等,我该如何专门化类?
正是如此,专长:
template <typename A>
class something<A,A> { ... }
模板使用模式匹配作为参数列表,如许多函数式编程语言中所见。
如何测试A和B类型是否属于同一类型?
您可以使用std::is_same
,或使用上述专业化。这取决于您的确切用例。
答案 1 :(得分:3)
您可以使用以下方法检查类型是否相同:
std::is_same<A, B>::value
它们会在真实时返回。
答案 2 :(得分:1)
这个怎么样
template <typename A, typename B>
struct EnsureSameType {};
template <typename A>
struct EnsureSameType<A, A> {
typedef int the_template_types_are_different;
};
int main()
{
/* this should compile */
typedef EnsureSameType<std::string::value_type, char>::the_template_types_are_different _;
/* this should fail, and you will see the compiler
remind you that the_template_types_are_different */
typedef EnsureSameType<std::string::value_type, wchar_t>::the_template_types_are_different _;
return 0;
}