Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 编译错误-模板,如果_C++_Templates_Enable If - Fatal编程技术网

C++ 编译错误-模板,如果

C++ 编译错误-模板,如果,c++,templates,enable-if,C++,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);

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

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);
}
模板
阶级公民{
公众:
公民(T健康,T年龄);
公民(T健康、T年龄、T攻击力);
T getHealth()常量{return\u health;};
T getAge()常量{return_age;};
T getAttackPower();
空腔损伤(T损伤);
私人:
健康;
T_年龄;
T_攻击力;
};
模板
公民::公民(T健康,T年龄):
_卫生(卫生),,
_年龄
{

static_assert(minAge_age您将
Citizen
声明为包含5个模板参数的类模板:

template <typename T, T, T, bool, typename >
class Citizen { ... };
template <typename T, T minAge, T maxAge, bool isarmed>
Citizen<T, minAge, maxAge, isarmed>::Citizen(T health, T age) 
模板
阶级公民{…};
然后尝试仅使用4个模板参数定义构造函数:

template <typename T, T, T, bool, typename >
class Citizen { ... };
template <typename T, T minAge, T maxAge, bool isarmed>
Citizen<T, minAge, maxAge, isarmed>::Citizen(T health, T age) 
模板
公民::公民(T健康,T年龄)
没有以前声明的4-template-parameter
Citizen
,因此出现错误。您仍然需要最后一个模板参数



请注意,这里的SFINAE没有多大意义,除非您有一些其他非算术的
Citizen
类模板(它本身没有多大意义)如果我没有弄错的话,SFINAE是用来解决函数模板的重载问题的。我不认为你可以将它用于类模板。@RSahu当然可以。那是@Barry,谢谢你的链接。我还没有弄清楚关于SFINAE的基本知识。现在,怎么办如果我想为两个场景声明Ctor。一个为isarmed==true,反之亦然?第五个模板参数有一个默认类型。为什么编译器不从第一个模板参数派生它?@RSahu有一个默认值。这并不意味着用户不能提供一个不是默认值的。那么,为什么是
Citizen::Citizen(T health,T age)
有问题吗?@RSahu因为
Citizen
不需要4个模板参数。需要5个。这里没有模板实例化。