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

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

相关内容

热门资讯

透视实锤!aapoker怎么设... 透视实锤!aapoker怎么设置抽水(透视)ai插件(竟然有挂)运aapoker怎么设置抽水辅助工具...
透视安装!aa poker辅助... 透视安装!aa poker辅助(透视)透视脚本(本来真的有挂);1、aa poker辅助透视辅助简单...
透视有挂!aapoker免费透... 透视有挂!aapoker免费透视脚本(透视)透视脚本下载(好像是有挂);1、实时aapoker免费透...
透视好友!aapoker辅助怎... 透视好友!aapoker辅助怎么用(透视)真的假的(总是有挂)1、aapoker辅助怎么用系统规律教...
透视有挂!aapoker辅助插... 透视有挂!aapoker辅助插件工具(透视)辅助(切实是真的有挂);aapoker辅助插件工具软件透...
透视透视!aapoker免费透... 透视透视!aapoker免费透视脚本(透视)透视脚本(一直有挂);在进入aapoker免费透视脚本辅...
透视最新!aapoker辅助工... 透视最新!aapoker辅助工具安全吗(透视)真的假的(一贯真的是有挂);aapoker辅助工具安全...
透视挂!aapoker插件下载... 透视挂!aapoker插件下载(透视)脚本(好像存在有挂)1、下载好aapoker插件下载辅助软件之...
透视软件!aapoker真的假... 透视软件!aapoker真的假的(透视)真的假的(其实有挂)在进入aapoker真的假的辅助挂后,参...
透视教学!aapoker俱乐部... 透视教学!aapoker俱乐部靠谱吗(透视)ai插件(其实真的是有挂)1、首先打开aapoker俱乐...