参数值相等时的模板特化

Ben*_*nes 7 c++ templates specialization template-specialization

我有一个表格的功能

template<int a, int b>
void f();
Run Code Online (Sandbox Code Playgroud)

当a == b时,我想专攻.伪代码看起来像:

template<int a>
void f<a, a>(){ //something}

template<int a, int b>
void f<a, b>(){ //something different}
Run Code Online (Sandbox Code Playgroud)

这是否可能没有部分模板专业化问题?

编辑:感谢您的快速回复.该方法实际上是在类中,更像是这样:

<typename a> class A{ 
    template<int b, int c> f(); 
}; 

A inst; 
inst.f<1,1>(); 
inst.f<1,2>(); 
Run Code Online (Sandbox Code Playgroud)

And*_*owl 7

您不能部分专门化功能模板,但可以部分地专门化类模板.

这为以下技巧留下了空间,其中实际工作由主函数模板的静态成员函数和专用函数模板完成,原始f()函数将其委托给它负责:

#include <iostream>

namespace detail
{
    template<int A, int B>
    struct helper
    {
        static void call() { std::cout << "f<A, B>()" << std::endl; }
    };

    template<int A>
    struct helper<A, A>
    {
        static void call() { std::cout << "f<A, A>()" << std::endl; }
    };
}

template<int a, int b>
void f()
{
    detail::helper<a, b>::call();
}
Run Code Online (Sandbox Code Playgroud)

这是你如何使用你的f()功能模板:

int main()
{
    f<1, 2>();
    f<1, 1>();
}
Run Code Online (Sandbox Code Playgroud)

这是一个实例.

编辑:

如果你的函数模板是一个成员函数,事情会变得稍微复杂一些,但上面提到的将函数模板局部特化转化为类模板局部特化的解决方案仍然可行.

这是您根据评论中提供示例进行操作的方法.

首先,向前声明helper类模板并授予其实例化访问类模板A的私有成员的权限(附加类型参数的角色T将在稍后变得清晰):

namespace detail
{
    template<typename T, int A, int B>
    struct helper;
}

template <typename a>
class A
{
public:
    template<int b, int c>
    void f();
private:
    template<typename, int, int> friend struct detail::helper;
};
Run Code Online (Sandbox Code Playgroud)

然后,您将helper像以前一样定义类模板及其特化,但是将函数参数添加call()到操作f()调用了原始成员函数的类对象所需的类型的函数中:

namespace detail
{
    template<typename T, int A, int B>
    struct helper
    {
        static void call(T* p) { std::cout << "f<A, B>()" << std::endl; }
    };

    template<typename T, int A>
    struct helper<T, A, A>
    {
        static void call(T* p) { std::cout << "f<A, A>()" << std::endl; }
    };
}
Run Code Online (Sandbox Code Playgroud)

然后你可以定义成员函数f(),如下所示:

template<typename a>
template<int b, int c>
void A<a>::f()
{
    detail::helper<A<a>, b, c>::call(this);
}
Run Code Online (Sandbox Code Playgroud)

并最终以这种方式使用它:

int main()
{
    A<int> inst;
    inst.f<1,1>();
    inst.f<1,2>();
}
Run Code Online (Sandbox Code Playgroud)

这个都放在这个实例中.