我在犹豫如何组织用 C++ 实现 SHA2 算法。
我的犹豫是因为 SHA2 可以通过 4 种方式实现,从而产生 4 种不同的摘要大小(224、256、384 和 512 位)。
我正在考虑专门用于可以使用 SHA2 生成的摘要大小的模板类。那么问题是非专业课要写什么。我能想到一些可能性:
//1 : throw exception on instantiation.
template<size_t bits> class SHA2 : public HashAlgorithm<Bits,Bits>{
public:
SHA2(){
throw SHA2NotImplementedException(bits);
}
virtual ~SHA2() throw(){}
virtual Bits hash(const Bits& data)const = 0;
}
//2 : throw exception on use.
template<size_t bits> class SHA2 : public HashAlgorithm<Bits,Bits>{
public:
virtual ~SHA2() throw(){}
virtual Bits hash(const Bits& data)const{return SHA2NotImplementedException(bits);}
}
//3 : forbid instantiation and inheritance.
template<size_t bits> class SHA2 : public HashAlgorithm<Bits,Bits>{
private:
SHA2(){}
public:
virtual ~SHA2() throw(){}
virtual Bits hash(const Bits& data)const = 0;
}
//4 : forbid instantiation.
template<size_t bits> class SHA2 : public HashAlgorithm<Bits,Bits>{
public:
virtual ~SHA2() throw(){}
virtual Bits hash(const Bits& data)const = 0;
}
//5 : dummy return.
template<size_t bits> class SHA2 : public HashAlgorithm<Bits,Bits>{
public:
virtual ~SHA2() throw(){}
virtual Bits hash(const Bits& data)const{return Bits();}
}
//Write template specialization for bits = 224, 256, 384 and 512
那么,你会写什么?哪个选项比其他选项更清晰,为什么?
附言:我也可以只编写 4 个独立的算法,而无需调整****代码风格。
最佳答案
如果您使用模板参数,该值必须在编译时可用。如果没有可能的实现,等到运行时才标记错误似乎很愚蠢。
所以不指定未指定的非专用模板,让它产生编译时错误。
关于C++ 代码风格 : SHA2 algorithm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191859/