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

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

相关内容

热门资讯

透视好友!wejoker辅助脚... 透视好友!wejoker辅助脚本,we poker辅助器v3.3,手段教程(都是是真的挂)-哔哩哔哩...
透视后台!hhpoker是真的... 透视后台!hhpoker是真的还是假的(透视)开挂辅助技巧(一直真的是有挂)-哔哩哔哩1、游戏颠覆性...
透视真的!wpk德州局怎么透视... 透视真的!wpk德州局怎么透视,智星菠萝可以辅助吗,诀窍教程(本来是真的挂)-哔哩哔哩1、这是跨平台...
透视代打!hhpoker破解工... 透视代打!hhpoker破解工具(透视)开挂辅助神器(切实存在有挂)-哔哩哔哩1、全新机制【hhpo...
透视好牌!菠萝辅助器免费版的特... 透视好牌!菠萝辅助器免费版的特点,hhpoker透视脚本,教程书教程(都是是有挂)-哔哩哔哩1、每一...
透视开挂!hhpoker有没有... 透视开挂!hhpoker有没有辅助挂(透视)开挂辅助插件(确实真的有挂)-哔哩哔哩在进入hhpoke...
透视软件!wpk辅助购买,we... 您好,wepoker是不是有人用挂这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
透视教程!wpk官网下载链接(... 透视教程!wpk官网下载链接(透视)开挂辅助挂(一直是有挂)-哔哩哔哩;1、透视教程!wpk官网下载...
透视透视!模拟器打开hhpok... 透视透视!模拟器打开hhpoker,哈糖大菠萝辅助器,手册教程(本来有挂)-哔哩哔哩1、超多福利:超...
透视德州版!hardrock辅... 透视德州版!hardrock辅助(透视)开挂辅助插件(确实有挂)-哔哩哔哩1)hardrock辅助辅...