如果变量的值在编译时已知/未知,则特殊化
Specialize if value of a variable is known/unknown at compile time
如何专门化模板函数的情况下,它的参数之一的值是已知/未知在编译期间(在实际编译和运行程序之前)?
我还不知道怎么做。
想法一:
#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
想法二:
#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.
我想你指的是参数的类型,对吧?对于部分模板特化,值无关紧要…
然后:这不可能。
模板的参数类型必须在编译时已知。编译器还应该如何生成正确的代码?
同样,对于部分模板特化,由于同样的原因,类型必须在编译时已知。
我来得有点晚了,我的部分答案可能不太令人满意,但下面是:
编译时无法通过检查判断值是否已知的情况:
-
constexpr
函数的非模板输入值 - 模板参数提供的类型的成员
我不知道如何处理问题1
,但对于问题2
,我们可以使用SFINAE
:寻找具有已知名称的特定成员(在下面的示例中为X
),并尝试将其作为模板参数发送,如下所示:
// like std::void_t, but for value inputs:
template <auto>
using v_to_void_t = void;
//////////////////////////////////////////////////////////////
template <class, class = void>
struct has_constexpr_X
: std::false_type {};
template <class T>
struct has_constexpr_X <T, v_to_void_t<T().X>>
: std::true_type {};
template <class T>
constexpr bool has_constexpr_X_v
= has_constexpr_X<T>::value;
使用例子:
struct HasStaticConstexprX {
static constexpr int X = 2;
};
struct HasStaticConstX {
static const int X; // implied constexpr
};
const int HasStaticConstX::X = 3;
struct HasStaticX {
static int X;
};
int HasStaticX::X = 4;
struct HasConstX {
const int X;
};
int main () {
static_assert(has_constexpr_X_v<HasStaticConstexprX>);
static_assert(has_constexpr_X_v<HasStaticConstX>);
static_assert(! has_constexpr_X_v<HasStaticX>);
static_assert(! has_constexpr_X_v<HasConstX>);
}
演示:
- c++ 17
- c++ 14
相关文章:
- 继承期间显示未知行为的子类
- 输入中的字符串数未知(以字母表示)
- 具有未知值时的时间复杂性
- 链表中写入访问冲突的未知原因
- 正在生成未知类实例
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 读取文件时运行时的未知行为
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 初始化多个未知基类
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- 如何存储未知次数迭代的输入?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 编译 Boost 时在 OS X 上的"ld:未知选项:-soname"
- 未知的 CMake 命令"create_single_source_cgal_program"
- 如何在C++中循环访问未知对象方法?
- Coursera :自动评分器的未知信号 11
- 即使直接从官方示例中复制,也找不到未知类型名称QML_ELEMENT和 QML 模块
- 未知的 GCC 链接器错误,但已成功构建
- 如何从未知视图中声明范围::v3::View 变量
- 如果变量的值在编译时已知/未知,则特殊化