简体   繁体   English

专门化成员函数,但不是整个类

[英]Specialize a member function but not entire class

I have a template the works with enums 我有一个模板与枚举的工作

template<typename T> class Enumuzaorous : public someclass<T>
{
public:
virtual ~Enumuzaorous() { } ;
virtual void do_this() { ... }
virtual void take_that() { ... }
virtual bool check_something() { return false; } 
T m_value;
}

I have many Enums that use this class and one more enum : 我有很多枚举使用这个类和一个枚举:

enum myLovelyEnum
{
today,tomorrow
}

For this enum I would like that check_something won't return false but do the following : 对于这个枚举,我希望check_something不会返回false,但执行以下操作:

bool check_something() { return m_value == today; } 

I can specialize the entire class for the enum, but I would need to copy&paste the implementation of: void do_this() { ... } void take_that() { ... } 我可以将整个类专门用于枚举,但我需要复制并粘贴以下实现: void do_this() { ... } void take_that() { ... }

Is it possible to specialize only one member function ? 是否可以只专门化一个成员函数? I guess not. 我猜不会。

Maybe I should Inherit and then specialize ? 也许我应该继承然后专攻?

What is the correct approach. 什么是正确的方法。 Maybe I can call from the specialized do_this, take_that to the generic ones ? 也许我可以从专业的do_this打电话,把它拿到通用的那个?

Thanks. 谢谢。

Member functions of class template are themselves function templates and can be explicitly specialized: 类模板的成员函数本身就是函数模板,可以明确地专门化:

template <>
bool Enumuzaorous<myLovelyEnum>::check_something()
{
     return m_value == today;
}

Another solution can be to use a traits class 另一种解决方案可以是使用特征类

template <typename T> struct DefaultEnumuzaorousTraits
{
  constexpr static bool check_something_impl(T&) { return false; }
};

template<typename T, class Traits = DefaultEnumuzaorousTraits<T>>
class Enumuzaorous : public someclass<T>
{
   // stuff omitted for brevity
   bool check_something() { return Traits::check_something_impl(m_value); }
};

struct DefaultEnumuzaorousTraits<myLovelyEnum>
{
  constexpr static bool check_something_impl(myLovelyEnum e) 
  { return e == myLovelyEnum::today; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM