Qub*_*ub1 2 c++ sfinae template-specialization
我是SFINAE的新手,我正在尝试编写一个简单的矢量模板.我想要实现的是根据为Vector设置的维度启用z成员变量.
我试图使用以下代码实现此效果:
template<unsigned int DIMENSIONS>
class Vector {
// The x and y variables (same as z)
template<typename = typename std::enable_if<DIMENSIONS >= 3>::type>
/// <summary>
/// The z coordinate.
/// </summary>
Float& z;
Vector() : x(values[0]), y(values[1]) {
}
// Other member functions and variables
std::vector<float> values;
};
template <>
Vector<3>::Vector() : x(values[0]), y(values[1]), z(values[2]) {
}
Run Code Online (Sandbox Code Playgroud)
这应该在有3个或更多维度时启用z变量.这使编译器抱怨以下错误:
'Vector<DIMENSIONS>::z': only static data member templates are allowed
Run Code Online (Sandbox Code Playgroud)
另外,在这种情况下,我不完全确定如何在SFINAE中使用初始化列表.因为如果维度小于3,则不必初始化z(因为它不存在).到目前为止,我已经使用了专门的3D向量构造函数(参见上面的代码).
但智能感知仍在报道 Members 'x', 'y', 'z' are not initialized in this constructor.
任何帮助,将不胜感激.
你可以这样做:
struct no_z_var {};
struct z_var
{
float z;
};
template<std::size_t n>
struct my_vector : std::conditional_t<( n >= 3 ), z_var, no_z_var>
{
float x, y;
};
int main()
{
my_vector<3> mv3;
mv3.z = 3.4f;
my_vector<2> mv2;
mv2.z = 3.4f; // error; no 'z'
}
Run Code Online (Sandbox Code Playgroud)
但是,这是一个很好的解决方案/设计吗?我不确定; 它会变得混乱.在实施过程中很可能会出现其他困难......