Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.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++ 使派生类跟随trait_C++_Typetraits - Fatal编程技术网

C++ 使派生类跟随trait

C++ 使派生类跟随trait,c++,typetraits,C++,Typetraits,假设我有一个基类 class Base {}; std::is_平凡::valueistrue。有没有一种方法可以强制所有从Base派生的类都是平凡的 换句话说,如何修改Base,从而导致编译错误 class Derived : public Base { Derived() {} }; 不要编写构造函数: #include <iostream> #include <type_traits> #include <cassert> struct A

假设我有一个基类

class Base {};
std::is_平凡::value
is
true
。有没有一种方法可以强制所有从
Base
派生的类都是平凡的

换句话说,如何修改
Base
,从而导致编译错误

class Derived : public Base {
    Derived() {}
};

不要编写构造函数:

#include <iostream>
#include <type_traits>
#include <cassert> 
struct A {
    int m;
};

struct B : A{
    B() {}
};

struct C : A{
    C() = default;
};

int main() 
{
    assert( std::is_trivial<A>{});
    assert(!std::is_trivial<B>{});
    assert( std::is_trivial<C>{});
}
#包括
#包括
#包括
结构A{
int m;
};
结构B:A{
B(){}
};
结构C:A{
C()=默认值;
};
int main()
{
断言(std::is_平凡{});
assert(!std::is_平凡{});
断言(std::is_平凡{});
}
要执行“强制”部分更为棘手,您可以设置一个约束,但使用CRTP

#include <iostream>
#include <type_traits>
#include <cassert> 

template<class D>
struct A {
    int m;
    static void enforce(){static_assert(std::is_trivial<D>{},"");}
};

/*struct B : A<B>{
    B() {}
};*/

struct C : A<C>{
    C() = default;
};

int main() 
{
//    assert( std::is_trivial<A>{});
//    assert(!std::is_trivial<B>{});
    assert( std::is_trivial<C>{});

}
#包括
#包括
#包括
模板
结构A{
int m;
static void exforce(){static_assert(std::is_平凡{},”);}
};
/*结构B:A{
B(){}
};*/
结构C:A{
C()=默认值;
};
int main()
{
//断言(std::is_平凡{});
//assert(!std::is_平凡{});
断言(std::is_平凡{});
}

您是否特别询问了
private
继承的使用?在我看来,这是不可能的。另一方面,如果你降低你的要求,这是可能的。可以检查从
Base
派生并在特定函数中使用的类型是否微不足道。为什么你需要这种特质是真的?我认为YSC是正确的。我想你可以使用CRTP,但你不能检查派生类是否平凡,因为它在基类中不完整。@NathanOliver,你也不能强制子类的编写器欺骗或滥用CRTP。既然平凡类不能是多态的,你为什么要在意呢?