gpt4 book ai didi

c++ - 模板参数的模板类型推导

转载 作者:太空狗 更新时间:2023-10-29 19:40:11 26 4
gpt4 key购买 nike

我知道,在给定特定函数参数的情况下,存在函数模板自动类型推导的可能性,但是对于非类型模板参数是否也存在这样的方法?

例子:

#include <iostream>

template<typename T, T val>
void func_a(void) {
std::cout << val << std::endl;
}

template<typename T>
void func_b(T val) {
std::cout << val << std::endl;
}

int main(void) {
func_a<uint32_t, 42u>();
//func_a<42u>(); //This line doesn't work
func_b(42u);
return 0;
}

所以我不想每次都给模板参数类型 uint32_t,当我调用 func_a() 时。 C++17以下有没有这样的方法?

我正在使用 g++ v.7.3 和 c++17。

最佳答案

在C++17中,你可以使用auto:

template<auto val>
void func_a(void) {
std::cout << val << std::endl;
}

int main(void) {
func_a<42u>();
return 0;
}

关于c++ - 模板参数的模板类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49499678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com