0

我正在犹豫如何在 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

那么,你会写什么呢?哪个选项比其他选项更清晰,为什么?

PS:我也可以只写 4 个独立的算法,而不需要与代码风格相匹配

4

2 回答 2

2

如果您使用模板参数,则该值必须在编译时可用。如果没有可能的实现,等到运行时标记错误似乎很愚蠢。

所以不要指定未指定的非专业模板,让它产生编译时错误。

于 2013-03-03T22:50:39.357 回答
1

把它完全留空(没有声明成员函数或变量)......为什么不呢?如果不使用非专业类,那是标准技术。

模板实例化不必具有相同的接口:它们基本上是完全独立的类

于 2013-03-03T22:49:34.217 回答