qin*_*l97 3 c++ templates c++11
问题简述如下:
template <typename T>
void display(T data){
if(is_int(T)) // how to check if T is int in this function is_int
printf("<int> %d", data);
if(is_float(T)) // how to check if T is float in this function is_float
printf("<int> %f", data);
if(is_class(T)) // how to check if T is class in this function is_class
data.display();
}
Run Code Online (Sandbox Code Playgroud)
这里假设T可以是int或float的类型或类.
如果我定义了一些变量并希望使用相同的函数显示它们的值:
int a = 10:
float b = 2.7;
A_Class c;
display(a);
display(b);
display(c);
display(new int(3));
display(new float(1.899));
display(new float(1));
Run Code Online (Sandbox Code Playgroud)
我知道在C++中,有一个用于检查int和float的解决方案(仅用于打印问题),即使用std :: cout,如本问题中所述(C++模板 - 如何查找模板类型是否为基本类型或类).
使用std :: is_integral :: value不适用于这样的情况:
display(new int(3));
display(new float(1.899));
display(new float(1));
Run Code Online (Sandbox Code Playgroud)
因为这些变量不是基本类型的类.那么对于这种情况,我们如何判断new int(),new float()的类型(int或float)?
要打印int和float值,只需分别提供display()那些类型参数的重载.对于包含名为成员函数的对象,display()可以使用SFINAE选择性地启用自由函数形式display()
#include <iostream>
#include <type_traits>
template<typename T>
auto display(T const& t) -> decltype(t.display(), void())
{
std::cout << "display(T const& t)\n";
}
void display(int)
{
std::cout << "display(int)\n";
}
void display(double)
{
std::cout << "display(double)\n";
}
struct foo
{
void display() const
{
std::cout << "foo::display\n";
}
};
struct bar {};
int main()
{
display(10);
display(10.0);
display(foo());
// display(bar()); // doesn't compile
}
Run Code Online (Sandbox Code Playgroud)
现场演示你打电话时会发生什么display(bar());
main.cpp:35:18: error: no matching function for call to 'display(bar)'
display(bar()); // doesn't compile
...
main.cpp:5:49: error: 'const struct bar' has no member named 'display'
Run Code Online (Sandbox Code Playgroud)
您直接提供版本,检查由以下人员提供<type_traits>:
template <typename T>
typename std::enable_if<std::is_same<T, int>::value>::type
display(T data){
printf("<int> %d", data);
}
template <typename T>
typename std::enable_if<std::is_same<T, float>::value>::type
display(T data){
printf("<int> %f", data);
}
template <typename T>
typename std::enable_if<std::is_class<T>::value>::type
display(const T& data){ // you probably don't want to copy the argument
data.display();
}
Run Code Online (Sandbox Code Playgroud)