C++ 函数模板返回值指定

C++函数模板不能偏特化,可以全特化。另外,返回值也是可以用static_cast指定的。
举例如下:

template<typename T1, typename T2, typename T3>
T1 add(T2 a, T3 b)
{
    return static_cast<int>(a + b);
}

指定T1为int,代码如下:

    int result = add<int>(0.4, 0.9);

指定T1, T2参数为int和float,代码如下:

int result = add<int, float>(0.4, 0.9);

一个完整的利用函数模板指定函数返回值的例子如下:

#include 

enum class AAA : int {
    TYPE1 = 33,
    TYPE2 = 52,
    TYPE3 = 92,
    TYPE4 = 102,
    TYPE5 = 22,
    TYPE6 = 8,
    TYPE7 = 12,
};

enum class BBB : int {
    TPYE1 = AAA::TYPE1,
    TYPE3 = AAA::TYPE3,
    TYPE5 = AAA::TYPE5,
};

enum class CCC : int {
    TPYE2 = AAA::TYPE2,
    TYPE3 = AAA::TYPE3,
    TYPE5 = AAA::TYPE5,
};

AAA uec2AAA (int uec) {
    AAA rc;
    switch (uec) {
        case 1: 
            rc = AAA::TYPE1;
            break;
        case 2:
            rc = AAA::TYPE2;
            break;
        case 3:
            rc = AAA::TYPE3;
            break;
        case 4:
            rc = AAA::TYPE4;
            break;
        case 5:    
            rc = AAA::TYPE5;
            break;
        case 6:
            rc = AAA::TYPE6;
            break;
        default:
            break;    
    }

    return rc;    
}

template<typename T1>
T1 uec2Rc(int a)
{
    return static_cast(uec2AAA(a));
}

int main(void)
{
    BBB result = uec2Rc(3);
    printf("result = %d\n", static_cast<int>(result));

    CCC result2 = uec2Rc(2);
    printf("result = %d\n", static_cast<int>(result2));

    return 0;
}

还有一些下次再写。

你可能感兴趣的:(C++)