不同类型的模板非类型参数
创始人
2025-01-09 08:00:07
0

在C++中,模板的非类型参数可以是整数、枚举、指针、引用、数组和对象等。下面是一些不同类型的模板非类型参数的代码示例:

  1. 整数类型的非类型参数:
template
void printValue() {
    std::cout << "Value is: " << N << std::endl;
}

int main() {
    printValue<10>(); // 输出: Value is: 10
    printValue<20>(); // 输出: Value is: 20
    return 0;
}
  1. 枚举类型的非类型参数:
enum class Color { Red, Green, Blue };

template
void printColor() {
    std::cout << "Color is: ";
    switch (C) {
        case Color::Red:
            std::cout << "Red";
            break;
        case Color::Green:
            std::cout << "Green";
            break;
        case Color::Blue:
            std::cout << "Blue";
            break;
    }
    std::cout << std::endl;
}

int main() {
    printColor();   // 输出: Color is: Red
    printColor(); // 输出: Color is: Green
    return 0;
}
  1. 指针类型的非类型参数:
template
void printPointerValue() {
    std::cout << "Value at the pointer: " << *Ptr << std::endl;
}

int main() {
    int value = 42;
    printPointerValue<&value>(); // 输出: Value at the pointer: 42
    return 0;
}
  1. 引用类型的非类型参数:
template
void printReferenceValue() {
    std::cout << "Value of the reference: " << Ref << std::endl;
}

int main() {
    int value = 42;
    printReferenceValue(); // 输出: Value of the reference: 42
    return 0;
}
  1. 数组类型的非类型参数:
template
void printArray() {
    std::cout << "Array values: ";
    for (int i = 0; i < N; ++i) {
        std::cout << Arr[i] << " ";
    }
    std::cout << std::endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    printArray<5, arr>(); // 输出: Array values: 1 2 3 4 5
    return 0;
}
  1. 对象类型的非类型参数:
class MyClass {
public:
    MyClass(int value) : value_(value) {}

    int getValue() const {
        return value_;
    }

private:
    int value_;
};

template
void printObjectValue() {
    std::cout << "Object value: " << Obj.getValue() << std::endl;
}

int main() {
    MyClass obj(42);
    printObjectValue(); // 输出: Object value: 42
    return 0;
}

这些示例展示了不同类型的模板非类型参数的使用方法。请注意,对于数组类型的非类型参数,需要将数组的大小作为额外的模板参数传递给模板函数。

相关内容

热门资讯

揭秘攻略!拱趴游戏破解器,we... 揭秘攻略!拱趴游戏破解器,wepokerplus万能挂,黑科技教程(有挂教程)1、点击下载安装,微扑...
透视辅助"wepok... 透视辅助"wepoker有没有挂"详细辅助必备教程(从来真的是有挂);小薇(透视辅助)致您一封信;亲...
实测发现!wepoker私局代... 实测发现!wepoker私局代打,xpoker辅助怎么用,透明教程(有挂攻略)1、不需要AI权限,帮...
透视存在"德州透视插... 透视存在"德州透视插件"详细辅助存在挂教程(固有真的有挂)1、玩家可以在德州透视插件软件透明挂俱乐部...
推荐十款!哈糖大菠萝挂,德普之... 推荐十款!哈糖大菠萝挂,德普之星透视,技巧教程(有挂透明)关于哈糖大菠萝挂机制的,其中提到了后台系统...
透视计算"wepok... 透视计算"wepoker俱乐部辅助"详细辅助切实教程(竟然存在有挂);支持多人共享记分板与复盘,通过...
玩家必看秘籍!hhpoker透... 玩家必看秘籍!hhpoker透视工具,哈糖大菠萝破解器,2025新版(有挂方法);1分钟了解详细教程...
透视好友"hhpok... 透视好友"hhpoker脚本下载"详细辅助2025新版教程(果然是真的有挂)准备好在hhpoker脚...
分享个大家!wepoker有辅... 分享个大家!wepoker有辅助插件吗,xpoker怎么作弊,线上教程(有挂辅助);实战中需综合运用...
透视线上"aa po... 透视线上"aa poker透视软件"详细辅助新2025版(本来有挂)是一款可以让一直输的玩家,快速成...