gpt4 book ai didi

c++ - CRTP - 从基类检查派生类是否满足要求

转载 作者:可可西里 更新时间:2023-11-01 18:29:12 24 4
gpt4 key购买 nike

奇怪的是,重复出现的模板模式可用于实现一种静态多态性。例如:

#include <iostream>

template<
class Derived
>
struct Base
{
static void print ( )
{
std::cout << Derived::number_to_print << '\n';
}
};

struct Derived final :
Base<
Derived
>
{
static constexpr unsigned int number_to_print = 27;
};

int main ( )
{
Derived::print();
}

这符合预期并打印出 27 .

现在,我想向基类添加检查以断言派生类满足某些要求。在上面给出的示例中,此类检查可能是:

#include <iostream>
#include <type_traits>

template<
class Derived
>
struct Base
{
// --- Checks begin
static_assert( std::is_same<
decltype(Derived::number_to_print),
unsigned int
>::value,
"static member `number_to_print' should be of type `unsigned int'" );
// --- Checks end

static void print ( )
{
std::cout << Derived::number_to_print << '\n';
}
};

struct Derived final :
Base<
Derived
>
{
static constexpr unsigned int number_to_print = 27;
};

int main ( )
{
Derived::print();
}

这行不通,因为在 Base<Derived> 的位置被实例化,Derived仅被前向声明,即,它是不完整的,除了它是一个结构这一事实之外,还不知道任何其他信息。

我一直在摸不着头脑,因为我认为这些检查可能会对基类的用户有所帮助,但还没有找到任何方法来做到这一点。

这可能吗?如果可能,怎么做?

最佳答案

作为noted by Kerrek SB您可以将静态断言移动到成员函数的主体中。

当你提供非static成员函数的功能时,而不是当前的static成员函数,你可以让断言函数体成为一个构造函数。

例如

#include <iostream>
#include <type_traits>
using namespace std;

#define STATIC_ASSERT( e ) static_assert( e, #e " // <- is required" )

template< class A, class B >
constexpr auto is_same_() -> bool { return std::is_same<A, B>::value; }

template< class Derived >
struct Base
{
Base()
{
STATIC_ASSERT((
is_same_< remove_cv_t< decltype( Derived::number_to_print ) >, int >()
));
}

void print() const
{
std::cout << Derived::number_to_print << '\n';
}
};

struct Derived final
: Base< Derived >
{
static constexpr int number_to_print = 27;
};

auto main()
-> int
{
Derived::Base().print();
}

关于c++ - CRTP - 从基类检查派生类是否满足要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com