c++ - 如何静态断言模板枚举类型? (C++11)

标签 c++ c++11 enums

enum PieceType
{
    NoPieceType, Pawn, Knight, Bishop, Rook, Queen, King,
    AllPieces = 0,
    PieceType_N = 8
};

template<PieceType T> Score OutpostEvaluator()
{
    static_assert(T == Bishop || T == Knight); // Doesn't compile.....
}

我想确保模板函数只能用于某些类型的枚举值,在我这里是 Bishop 和 Knight。 std::is_scalar()、std::is_enum() 和其他类型支持在我的情况下似乎不起作用。如何实现?

最佳答案

static_assert 的语法,来自 http://en.cppreference.com/w/cpp/language/static_assert .

static_assert ( bool_constexpr , message );

您需要提供一条消息。像这样的东西:

static_assert(T == Bishop || T == Knight, "Expected Bishop or Knight");

关于c++ - 如何静态断言模板枚举类型? (C++11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835241/

相关文章:

c++ - 从这个对象的方法开始的线程中销毁类对象的最佳实践

swift - 如何访问 Swift 中其他类中的枚举值?

java - Java 中枚举的缺点是什么?

c++ - Cholesky 分解 ScaLapack 错误

c++ - Qt:从 View 中删除模型

c++ - 从 C++ 访问表中的 Lua 表

C++11随机数生成器UIntType矛盾

c++ - 将常量 unique_ptr 设为常量 vector

c++ - 未经初始化打印随机符号

c# - 为什么具有默认值的枚举在 C# 中不能按预期工作?