gpt4 book ai didi

c++ - 专门化变量的值在编译时是否已知/未知

转载 作者:可可西里 更新时间:2023-11-01 16:47:23 26 4
gpt4 key购买 nike

如果在编译期间(在实际编译和运行程序之前)其参数之一的值已知/未知,如何专门化模板函数?

我还不知道怎么做。

想法 1:

#include <type_traits>
#include <iostream>
int main(void){
int a; //value of a is not known at compile time
bool b = (a == a); //value of b is known at compile time.
std::is_assignable< constexpr bool, bool >::value
}
//g++ magic.cpp -std=c++14
//error: wrong number of template arguments (1, should be 2)
// std::is_assignable< constexpr bool, bool >::value

想法 2:

#include <type_traits>
#include <iostream>
int main(void){
const int a=1;
int b = (a == a);
std::cout << __builtin_constant_p (a) << std::endl;
std::cout << __builtin_constant_p (b) << std::endl;
}
//prints 0 and 0.

最佳答案

嗯,我猜你指的是参数的类型,对吧?值对于部分模板特化无关紧要...

那么:这不行。

模板的参数类型必须在编译时已知。编译器还应该如何生成正确的代码?

对于部分模板特化,出于同样的原因,类型必须在编译时已知。

关于c++ - 专门化变量的值在编译时是否已知/未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39742883/

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