如何确定模板类型是基本类型还是类
How to determine whether the template type is a basic type or a class
我有这样的代码
template <typename T> void fun (T value)
{
.....
value.print (); //Here if T is a class I want to call print (),
//otherwise use printf
.....
}
现在,要打印值,如果T是一个类,我想调用对象的print函数,但如果T是一个基本数据类型,我只想使用printf。
那么,我如何发现模板类型是基本数据类型还是类?
您可以使用std::is_class
(也可能是std::is_union
)。细节取决于你对"基本类型"的定义。查看更多关于类型支持的信息
但是请注意,在c++中,通常重载std::ostream& operator<<(std::ostream&, T)
来打印用户定义的类型T
。这样,您就不需要担心传递给函数模板的类型是否是类:
template <typename T> void fun (T value)
{
std::cout << value << "n";
}
建议对任何类型的T
重载operator<<(std::ostream&)
,而不是使用printf()
:您如何知道使用哪种格式说明符?
template <typename T> void fun (T value)
{
.....
std::cout << value << std::endl;
.....
}
std::is_class
存在
如果您没有c++ 11的支持,可以选择。
template<typename T>
class isClassT {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
template<typename C> static Two test(…);
public:
enum { Yes = sizeof(isClassT<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
一个简单的模板,用来判断type是否为类类型。c++模板完整指南中的更多内容。if (isClassT<T>::Yes) {
std::cout << " Type is class " << std::endl;
}
我会使用打印辅助函数模板/overload:
template <typename T>
void print(T const & t) { t.print(); }
template <typename U>
void print(U * p) { std::printf("%p", static_cast<void*>(p)); }
// we really an enable_if on is_object<U>::value here...
void print(char x) { std::printf("%c", x); }
void print(int x) { std::printf("%d", x); }
// etc. for all fundamental types
那么您可以简单地在代码中使用print(value);
相关文章:
- 是否可以根据其数据成员的类型确定类型的大小
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 如何确定捕获不可复制参数的 lambda 的类型?
- 如何确定涉及 C++ 中除法的算术表达式的数据类型
- 如何确定模板的返回类型?
- 用于确定 C++ 中对象的类型的语句
- 是否可以确定枚举是否为强类型?
- 使用C++11标准的哪些规则来确定({..})中表达式的类型
- 确定大层次结构中基本指针的实际类型,无需dynamic_cast
- 使用std::conditional中的模板来确定函数参数类型
- 如何确定迭代器在 c++ 模板函数中指向的对象的类型?
- 如何根据用户输入确定容器类型
- 确定 opencv c++ 中 StatModel 的类型
- 你能用同样的方式确定所有类类型的大小吗?
- 在通用 lambda 中使用 constexpr-if 来确定参数的类型
- C++ 从两类中确定无效类型*
- 给定这两种类型,我是否可以确定虚拟函数是否已被覆盖?
- 确定输入"conscalc: calc"的类型时出错。不能联合编码器。具有不同字段集的结构类型
- 乘法类型的确定
- 我可以通过类型特征确定指针是否为整型