编译错误 - 模板,enable_if

compile error - templates, enable_if

你能告诉我为什么这段代码不能编译吗?

template <typename T, T minAge, T maxAge, bool isarmed,
typename = std::enable_if_t<std::is_arithmetic<T>::value>>
class Citizen {
public:

    Citizen(T health, T age);
    Citizen(T health, T age, T attackPower);
    T getHealth() const { return _health; };
    T getAge() const { return _age; };
    T getAttackPower();
    void takeDamage(T damage);

private:
    T _health;
    T _age;
    T _attackPower;
};

template <typename T, T minAge, T maxAge, bool isarmed>
Citizen<T, minAge, maxAge, isarmed>::Citizen(T health, T age):
        _health (health),
        _age (age)
{
    static_assert(minAge <= maxAge, "Wrong age");
    assert(minAge <= this->_age && this->_age <= maxAge);
}

我错过了什么?

error: invalid use of incomplete type ‘class Citizen<T, minAge, maxAge, isarmed>’

您将 Citizen 声明为采用 5 个模板参数的 class 模板:

template <typename T, T, T, bool, typename >
class Citizen { ... };

然后尝试仅使用 4 个模板参数来定义构造函数:

template <typename T, T minAge, T maxAge, bool isarmed>
Citizen<T, minAge, maxAge, isarmed>::Citizen(T health, T age) 

没有这样的先前声明的 4 模板参数 Citizen,因此出现错误。您仍然需要最后一个模板参数。


请注意,除非您有其他一些非算术 Citizen class 模板(它本身没有多大意义),否则此处的 SFINAE 没有多大意义。只是 static_assert 因为 T 是算术类型。