C++ 专门化模板中的单个方法 class

C++ specialize single method in template class

我的情况是我有一个现有模板 class,它适用于所有类型的数据类型。但是现在我需要将它专门用于从特定 class 派生的 classes。但不是整个 class 应该专门化,而只是一些功能。

我试着按照 this post 中描述的那样去做。

class BaseClass
{
   public:

   bool DoSomething()
   {
       return true;
   }
};

class SubClass : BaseClass
{
};

template<typename T, typename _Alloc = std::allocator<T>>
class TemplateClass
{
   public:
    template<typename U = T, typename std::enable_if<
       !std::is_base_of<BaseClass, U>::value>::type>
    void print_line()
    {
       std::cout << "Parameter of general Type T" << std::endl;
    }

    template<typename U = T, typename std::enable_if<
       std::is_base_of<BaseClass, U>::value>::type>
    void print_line()
    {
       std::cout << "Parameter of specific Type BaseClass" << std::endl;
    }
};

我尝试使用这样的模板:

TemplateClass<BaseClass>* tc1 = new TemplateClass<BaseClass>();
tc1->print_line();

TemplateClass<SubClass>* tc2 = new TemplateClass<SubClass>();
tc2->print_line();

TemplateClass<int>* tc3 = new TemplateClass<int>();
tc3->print_line();

对于每个函数调用,我都收到错误消息,没有找到合适的方法。 另一点是,在 this article 中,他们说 enable_if 不应该用于 select 之间的实现。

有没有人知道我的错误是什么或者如何正确地做到这一点? 提前致谢!

您可以将其更改为

template<typename U = T, typename std::enable_if<
   !std::is_base_of<BaseClass, U>::value>::type* = nullptr>
void print_line()
{
   std::cout << "Parameter of general Type T" << std::endl;
}

template<typename U = T>
typename std::enable_if<!std::is_base_of<BaseClass, U>::value, void>::type print_line()
{
   std::cout << "Parameter of general Type T" << std::endl;
}

另一个相应。

两者背后的想法是在函数模板的实例化期间为其中一种方法产生错误。由于错误,在重载决议期间不考虑相应的方法,因此只有一种方法(未产生错误的方法)可用,然后将调用该方法。 std::enable_if 用于产生此错误,因为如果它的第一个参数是 false 它没有定义 type 成员,因此函数模板无法实例化并将从重载决议中删除。

搜索 SFINAE 了解更多详细信息。