我还在犹豫如何在SHA2中组织实现C++算法。
我犹豫不决的原因是,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那你会写什么?哪个选项比其他选项更清晰,为什么?
PS :我也可以编写4种不同的算法,而不需要使用代码样式。
发布于 2013-03-03 22:50:39
如果使用模板参数,则该值必须在编译时可用。如果没有可能的实现,等待运行时标记错误似乎很愚蠢。
因此,保留未指定的模板,让它生成编译时错误。
发布于 2013-03-03 22:49:34
只需将其保留为完全空(没有声明的成员函数或变量)...why,不是吗?如果不使用非专门类,这就是标准技术。
模板实例化不必有相同的接口:它们基本上是完全独立的类
https://stackoverflow.com/questions/15191859
复制相似问题