C++ 代码风格 : SHA2 algorithm

标签 c++ templates coding-style

我在犹豫如何组织用 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/

相关文章:

c++ - Windows 桌面复制 API 等效 IOS

c++ - Visual Studio 2013 c++ lambda 捕获参数包

C# 和 C++ 库

C++ 模板和不明确的函数调用

c++ - 为什么编译器选择下面的模板版本?

visual-studio - 谁喜欢 Visual Studio 中的#regions?

typescript - 干净的方式来尊重 DRY 的条件

c++ - winsock select()ing 运行时错误

php - 试图避免 "spaghetti code",为什么多个 if-else 不好?

c++ - 混合函数模板和普通函数