不同类型的模板非类型参数
创始人
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;
}

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

相关内容

热门资讯

透视中牌率!wepoker怎么... 透视中牌率!wepoker怎么获得好牌,微信大a辅助,线上教程(有挂介绍);1、很好的工具软件,可以...
透视好友!wepoker透视脚... 透视好友!wepoker透视脚本免费下载,789大菠萝有挂吗,曝光教程(有挂详情)1、首先打开789...
透视计算!wepoker透视脚... 透视计算!wepoker透视脚本免费下载pc,丫丫老陕开挂,技巧教程(有挂解说)1、透视计算!wep...
透视智能ai!htx矩阵wep... 透视智能ai!htx矩阵wepoker辅助,聚财平台辅助,普及教程(有挂技巧);1、聚财平台辅助透视...
透视好友!wepoker有机器... 透视好友!wepoker有机器人吗,潮友会app下载官方辅助器,2025新版教程(有挂辅助)1、下载...
透视黑科技!aapoker插件... 透视黑科技!aapoker插件,兴动海满辅助,规律教程(有挂插件)兴动海满辅助辅助器中分为三种模型:...
透视辅助!poker辅助器免费... 透视辅助!poker辅助器免费安装,开心游戏快跑辅助,靠谱教程(有挂揭秘)在进入开心游戏快跑辅助辅助...
透视有挂!wepoker-h5... 透视有挂!wepoker-h5下载,鱼乐达人脚本辅助,大神讲解(有挂脚本)1、进入到鱼乐达人脚本辅助...
透视新版!wepoker透视破... 透视新版!wepoker透视破解版,哈糖大菠萝辅助,详细教程(有挂规律);1、任何哈糖大菠萝辅助ai...
透视存在!we poker辅助... 透视存在!we poker辅助器v3.3,如何使用闽乐乐510k脚本,力荐教程(有挂规律);1、如何...