【发布时间】:2016-04-16 23:56:25
【问题描述】:
奇怪地重复出现的模板模式可以用来实现一种静态多态性。例如:
#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 只是被前向声明的,也就是说,它是不完整的,除了它是一个结构体这一事实之外,它一无所知。
我一直在摸不着头脑,因为我认为这些检查可能对基类的用户有所帮助,但还没有找到任何方法来做到这一点。
有可能吗?如果可以,怎么做?
【问题讨论】:
-
This page 很有用。