我打算让类'MyVector'具有3D坐标(X,Y,Z)。
我尝试使构造函数具有三种类型的函数参数,每种参数类型都满足std :: is_arithmetic。
我输入了两个不同的代码。一个运行良好,但另一个运行不正常。
这是我的代码。
main.cpp
#include <iostream>
#include "MyVector.h"
using namespace std;
int main()
{
MyVector mv1 = MyVector();
int x = 5;
double y = 2.0;
float z = 5.0;
MyVector mv2 = MyVector(z, y, x);
//MyVector mv3 = MyVector(&x);
cout << boolalpha << is_arithmetic<int>::value << endl;
cout << mv2;
}
MyVector.h
#pragma once
#include <type_traits>
#include <iostream>
class MyVector
{
public:
MyVector();
MyVector(const MyVector&);
//This is What I wanted
template <typename N1, typename = std::enable_if_t<std::is_arithmetic<N1>::value >
, typename N2, typename = std::enable_if_t<std::is_arithmetic<N2>::value >
, typename N3, typename = std::enable_if_t<std::is_arithmetic<N3>::value > >
MyVector(const N1& x, const N2& y, const N3& z)
{
X = x;
Y = y;
Z = z;
}
//Working
template <typename N, typename = std::enable_if_t<std::is_arithmetic<N>::value >>
MyVector(const N& x)
{
X = 0;
Y = 0;
Z = 0;
}
//Not Working
template <typename N, std::enable_if_t<std::is_arithmetic<N>::value >>
MyVector(const N& x)
{
X = 0;
Y = 0;
Z = 0;
}
private:
float X;
float Y;
float Z;
public:
friend std::ostream& operator<<(std::ostream&, const MyVector&);
};
我不知道下面两个代码的区别是什么
1. template <typename N, typename = std::enable_if_t<std::is_arithmetic<N>::value >>
2. template <typename N, std::enable_if_t<std::is_arithmetic<N>::value >>
这两行代码的操作方式略有不同。
template <typename N, typename = std::enable_if_t<std::is_arithmetic<N>::value
// or with type
template <typename N, typename def = std::enable_if_t<std::is_arithmetic<N>::value
将类型定义为模板参数(在第一种情况下未命名),因此本文有助于理解在哪里使用模板/类型名。鉴于
2. template <typename N, std::enable_if_t<std::is_arithmetic<N>::value >>
具有非类型的模板参数(在这种情况下,默认情况下未指定),因此您需要指定它或像[]那样写……]
3. template <typename N, std::enable_if_t<std::is_arithmetic<N>::value >* = nullptr>