当我在模板类中编写函数时,如何找出我的T是什么?
例如
template <typename T>
ostream& operator << (ostream &out,Vector<T>& vec)
{
if (typename T == int)
}
Run Code Online (Sandbox Code Playgroud)
如何编写上面的if语句以便它可以工作?
CB *_*ley 41
像这样的东西:
template< class T >
struct TypeIsInt
{
static const bool value = false;
};
template<>
struct TypeIsInt< int >
{
static const bool value = true;
};
template <typename T>
ostream& operator << (ostream &out,Vector<T>& vec)
{
if (TypeIsInt< T >::value)
// ...
}
Run Code Online (Sandbox Code Playgroud)
lee*_*mes 11
从C++ 11开始,我们有std::is_same:
if (std::is_same<T, int>::value) ...
Run Code Online (Sandbox Code Playgroud)
它的实现类似于TypeIsInt其他答案中建议的特征,但有两种类型需要比较.
Art*_*ger 10
明确定义它,例如:
template <>
ostream& operator << (ostream &out,Vector<int>& vec)
{
}
Run Code Online (Sandbox Code Playgroud)
jal*_*alf 10
最简单,最通用的解决方案:只需编写一个普通的旧函数重载:
ostream& operator << (ostream &out,Vector<int>& vec)
{
// Your int-specific implementation goes here
}
Run Code Online (Sandbox Code Playgroud)
这假设int和非int版本没有太多共同的代码,因为您必须编写两个单独的实现.
如果你想使用函数的一个常见实现,只是if里面的语句不同,请使用Charles Bailey的实现:
template< class T >
struct TypeIsInt
{
static const bool value = false;
};
template<>
struct TypeIsInt< int >
{
static const bool value = true;
};
template <typename T>
ostream& operator << (ostream &out,Vector<T>& vec)
{
if (TypeIsInt< T >::value) {
// your int-specific code here
}
}
Run Code Online (Sandbox Code Playgroud)
一般情况下,typeid如果您不需要,请不要使用.
小智 9
最简单的方法是提供模板专业化:
#include <iostream>
#include <vector>
using namespace std;
template <typename T> struct A {
};
template <typename T >
ostream & operator <<( ostream & os, A<T> & a ) {
return os << "not an int" << endl;
}
template <>
ostream & operator <<( ostream & os, A<int> & a ) {
return os << "an int" << endl;
}
int main() {
A <double> ad;
cout << ad;
A <int> ai;
cout << ai;
}
Run Code Online (Sandbox Code Playgroud)
这条路.
ostream & operator << (ostream &out, Vector<int> const & vec)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
如果通过,编译器将在函数模板上选择此函数Vector<int>.
编辑:我发现这篇文章试图解释为什么更喜欢重载到模板专业化.
小智 6
TypeID永远不是一个好主意.它依赖于RTTI.顺便说一句,这是你的答案:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.7