如何根据模板参数选择替代成员函数实现

How do I select an alternative member function implementation, depending on a template argument?

本文关键字:成员 函数 实现 选择 参数 何根      更新时间:2023-10-16

假设我有这个类:

template</*some other parameters here */class toggle>
class Foo
{
   void function();
   //Lots of other non-parametrized member functions
}

现在,如果toggle是某种特定类型的,我希望函数使用替代实现,对于所有其他情况,我希望它使用标准实现。这应该完全在编译时完成,因为类的外部用户应该能够实例化这个模板,而这个模板(为了节省内存和一点性能)缺乏一些功能。

问题是:简单地专门化整个类是不现实的,因为Foo将有很多其他方法不依赖于这种切换,而这种切换也必须再次实现,这使得一切都是巨大的空间浪费。

我想这就是你想要的:

#include <iostream>
#include <string>
template <class toggle>
class Foo
{
public:
    void function() { std::cout << "Defaultn"; }
};
template <>
void Foo<int>::function() { std::cout << "intn"; }
int main ()
{
    Foo<std::string>().function();
    Foo<int>().function();
    return 0;
}

输出:

Default
int

您可以专门化基类:

template<class toggle>
class FooFunction {
public:
    void function();
};
template<>
class FooFunction<blah> {
public:
    void function();
};
template<class toggle>
class Foo : public FooFunction<toggle> {
    //Lots of other non-parametrized member functions
};

如果使function成为一组重载的函数模板对您来说是可以接受的,那么:

// toggle is not a dependent type so we solve that
template<
    typename T = toggle
    , typename = typename std::enable_if<
        std::is_same<T, int>::value
    >::type
>
void function()
{ /* implementation for int */ }
template<
    typename T = toggle
    , typename = typename std::enable_if<
        !std::is_same<T, int>::value
    >::type
    // dummy parameter to make this declaration distinct from the previous one
    typename = void
>
void function()
{ /* implementation for others */ }

这是用C++11风格编写的,但可以使用C++03。(在某些情况下,这可能取决于SFINAE在某种程度上是C++03的灰色区域,但我对规则了解不够。)

模板专业化,尝试调试它,并注意并非所有功能都需要专业化:

template <class T> class Spec
{
public:
    void Func()
    {
    }
    void Func2()
    {
    }
};

void Spec<double>::Func()
{
}
int main( int argc, char *argv )
{
    Spec<int> spec1;
    spec1.Func();
    spec1.Func2();
    Spec<double> spec2;
    spec2.Func();
    spec2.Func2();

    return 0;
}