是否有方法从CRTP基类中查询派生类的内容,以便与SFINAE一起使用以启用或禁用基类方法?CRTP:基于派生类内容在基类中启用方法
我试图实现可能类似于以下内容:
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"; }
};
无非是想在一个错误引用无效使用不完整的类的使用Derived::foo
内enable_if
结果(衍生)。
谢谢!我的C++现在有些生疏,所以不记得如何影响模板评估的顺序;多余的模板就是我所追求的。我同意你的解决方案比enable_if更有趣;仍然需要学习使用C++ 11及更高版本的东西。 –