【发布时间】:2015-05-26 12:29:18
【问题描述】:
我想知道如何实现我在下面描述的内容。
考虑一个基础 CRTP 类,其中一个功能需要启用而另一个功能需要禁用。
这是通过取决于类型定义的特征类控制的。
我最好不想在我的特征类中定义任何东西,但如果它有助于将其定义为 void 我可以接受。 cmets 中的更多信息,因为在那里显示我想要实现的目标要容易得多。
template<class T>
struct Model_Traits;
// Base CTRP class
template<typename Model>
class BaseModel
{
inline const Model& impl() const { return static_cast<Model const&>(*this); }
// not sure how to enable this template or not based on my traits class
// which is necessary as some wont have it defined
using foo_t = typename Model_Traits<Model>::foo_t;
// this one should be enabled when foo_t is not defined
void optimize(const foo1& f1, const foo2& f2, foo3* f3)
{
impl().optimize(f1,f2,f3);
}
// this one should only be enabled if foo_t is defined
// not sure if this is correct
template<typename T = foo_t,
typename = std::enable_if<foo_t>::type>
void optimize(const foo1& f1, const foo2& f2, foo3* f3, foo_t* f4)
{
impl().optimize(f1,f2,f3, f4);
}
}
// First class defining the foo_t
template<MyModel>
struct Model_Traits
{
using foo_t = myFoo;
}
class MyModel : public BaseModel<MyModel>
{
void optimize(const foo1& f1, const foo2& f2, foo3* f3, foo_t* f4);
}
// Second class not defining foo_t
template<MyModel2>
struct Model_Traits
{
}
class MyModel2 : public BaseModel<MyModel2>
{
void optimize(const foo1& f1, const foo2& f2, foo3* f3);
}
我当然应该说这是简化的,我的代码看起来不像那样,但如果你把所有其他的东西都去掉,它就很接近了。
有什么想法吗?
【问题讨论】:
-
也许您可以使用“CppCon 2014:Walter E. Brown”现代模板元编程:纲要中的 void_t 技巧。此处显示了如何使用它来实现概念的示例:@987654321 @ 基本上,它是一种根据是否定义某些内容来重载模板的方法。