首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++代码样式: SHA2算法

C++代码样式: SHA2算法
EN

Stack Overflow用户
提问于 2013-03-03 22:47:23
回答 2查看 412关注 0票数 0

我还在犹豫如何在SHA2中组织实现C++算法。

我犹豫不决的原因是,SHA2可以以4种方式实现,从而产生4种不同的摘要大小(224、256、384和512位)。

我正在考虑一个模板类,专门用于可以用SHA2生成的摘要大小。接下来的问题是为非专业课写些什么。我能想到一些可能性:

代码语言:javascript
复制
//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种不同的算法,而不需要使用代码样式。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-03 22:50:39

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

因此,保留未指定的模板,让它生成编译时错误。

票数 2
EN

Stack Overflow用户

发布于 2013-03-03 22:49:34

只需将其保留为完全空(没有声明的成员函数或变量)...why,不是吗?如果不使用非专门类,这就是标准技术。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15191859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档