专门研究功能模板

ril*_*mat 0 c++ templates template-specialization

如何在c ++中专门化函数模板?

#include <iostream>

template <int X = 0>  //Wrong attempt, does not compile.
int func(int y)
{
    return X + y;
}

template<int X>
int func(int y)
{
    return X + func<X-1>(y);
}


int main()
{
    std::cout << func<1>(2);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我希望这个程序的结果是:1 + 0 + y = 3.

对于y = 2,它将是:2 + 1 + 0 + y.

我知道有更好的方法来进行这种计算,我试图理解这种语言的这个方面.

Joh*_*itb 5

通过委托重载该功能

template <int X>
class Int 
{
};

template <int X>
int funcSwitch(int y, Int<X>)
{
    return X + funcSwitch(y, Int<X-1>());
}

int funcSwitch(int y, Int<0>)
{
    return y;
}

template<int X>
int func(int y)
{
    return funcSwitch(y, Int<X>());
}

int main()
{
    std::cout << func<1>(2);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你需要注意不要Int在另一个命名空间中定义funcSwitch,因为那时第一个调用在实例化时funcSwitch不会找到第二种funcSwitch情况(这是因为一个名为ADL的规则).为了不考虑这一点,您还可以编写一个类模板来委托

template<int X>
struct FuncImpl {
    int operator()(int y) const {
        return X + FuncImpl<X-1>()(y);
    }
};

template<>
struct FuncImpl<0> {
    int operator()(int y) const {
        return y;
    }
};

template<int X>
int func(int y)
{
    return FuncImpl<X>()(y);
}

int main()
{
    std::cout << func<1>(2);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

一般来说,我更喜欢没有类的技术,因为它允许成员函数仍然访问*this,如果func是成员函数则允许其私有成员.

要完成,功能还有"明确的专业化",但由于其局限性和缺陷,我不推荐它.在这种情况下,它会起作用

template<int X>
int func(int y)
{
    return X + func<X-1>(y);
}


template <>
int func<0>(int y)
{
    return y;
}

int main()
{
    std::cout << func<1>(2);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)