【发布时间】:2020-05-12 22:58:45
【问题描述】:
我打算让“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 >>
【问题讨论】:
标签: c++ templates enable-if typename