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

标签 c++ templates metaprogramming

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

我还不知道怎么做。

想法 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/

相关文章:

c++ - 对大小为 n 的数组进行排序

c++ - 如何在 Qt 中围绕固定点设置动画?

c++ - Clang 中的嵌套 C 数组结构对齐

xml - 使用 Maven 生成 XML 文件

macros - 将列表传递给 Common Lisp 中的宏

c++ - 是否有适用于 iOS 的高级音频队列记录服务库?

c++ - 如何 typedef 模板类?

c++ - 使用 C++ 模板有条件地插入方法的主体

javascript - 对 JavaScript 函数进行非正则表达式重构的最快方法

c++ - boost::spirit::qi::parse 语法未按预期工作 - 第 2 部分