【发布时间】:2017-02-28 16:33:58
【问题描述】:
有没有办法从 CRTP 基类查询派生类的内容,与 SFINAE 一起使用以启用或禁用基类方法?
我想要完成的可能如下所示:
template<typename Derived>
struct base
{
struct foo {};
struct bar {};
void dispatch(int i)
{
switch (i) {
case 0: dispatch(foo{}); break;
case 1: dispatch(bar{}); break;
default: break;
}
}
// catch all for disabled methods
template<typename T> void dispatch(T const&) {}
std::enable_if</* magic that checks if there is in fact Derived::foo(foo) */>
dispatch(foo f)
{
static_cast<Derived*>(this)->foo(f);
}
std::enable_if</* magic that checks if there is in fact Derived::bar(bar) */>
dispatch(bar b)
{
static_cast<Derived*>(this)->bar(b);
}
};
struct derived: public base<derived>
{
// only foo in this one
void foo(foo) { std::cout << "foo()\n"; }
};
简单地尝试在enable_if 中使用Derived::foo 会导致错误引用不完整类(派生类)的无效使用。
【问题讨论】: