有没有办法在 c++ 中制作类型变量?
Is there a way to make a type variable in c++?
我很好奇一种制作类型变量的方法。 我的意思在下面的代码中解释:
using var = type_var<int>; // currently var is of type type_var<int>
/// somewhere like in constexpr functions
var::store<float>; // now var is of type type_var<float>
static_assert(std::is_same<var::get_type, float>::value, "");
当然,据我所知,这段代码永远不会起作用,因为using
会使var
"不可变"。
但是,我仍然想知道是否有一种方法可以可变地存储类型。
我在这个问题中要问的是,有没有办法使存储"类型"的元素在编译时可以更改元素中包含的类型。
简单的答案是否定的!
c++编程语言没有"编译时变量"之类的东西。所有内容都遵循一个定义规则 (ODR(
C++为模板提供了一种自己的编译时语言,通常称为模板元编程(TMP(TMP语言使用函数式编程语言的一般概念。
摘自上面的链接文本:
函数式程序没有赋值语句,也就是说,函数式程序中变量的值一旦定义就永远不会改变。
如果我理解你的伪示例代码,你会想到如下:
template < auto x >
struct Variable
{
static constexpr decltype(x) value = x;
};
Variable< 10 > intvar;
Variable< 'a' > charvar;
int main()
{
// accessing the data:
std::cout << intvar.value << std::endl;
std::cout << charvar.value << std::endl;
}
但是在模板和类型的世界中,您没有机会再为模板"分配"新值或类型,只需没有任何类型的语法即可。
您也可以在TMP中编程算法,但是"调用"的所有"结果"都不在任何种类变量中,它们总是定义新的"值"。
一些模板元编程的示例。该示例演示如何编写 "添加"功能"。它将添加两种类型的容器...
// define a data structure which can contain a list of types
template < typename ... TYPES >
struct TypeContainer;
// let us define some TMP "variables", which are types in c++
using list1 = TypeContainer<int, float, int >;
using list2 = TypeContainer< char, bool, int >;
// and now we define a TMP "function"
template < typename ... PARMS > struct Concat;
// which simply adds two typelists
template < typename ... LIST1, typename ... LIST2 >
struct Concat< TypeContainer< LIST1... >, TypeContainer< LIST2...>>
{
using RESULT = TypeContainer< LIST1..., LIST2...>;
};
using list3 = Concat<list1, list2 >::RESULT;
// But you never can change the "variable", because of the
// One Definition Rule (ODR)
// ( will fail to compile )
//using list2 = Concat<list1, list2 >::RESULT;
// helper to let us know what we have in the typelists:
// works for gcc or clang but is implementation specific
template < typename T>
void Print()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
int main()
{
Print<list3>();
}
你会发现这样的算法已经在STL中定义过。在那里,你有 std::tuple 作为类型容器,std::tuple_cat 来执行两个元组的"添加"。我的代码应该只给你一个简单的例子来理解我们在做什么,而不是从STL内部做一些神奇的事情。
相关文章:
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 指针数据类型变量如何包含对象?
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 如何为结构类型变量赋值
- 如何将字符类型变量附加到字符串中?
- 共享或私有 openmp 代码中的结构化类型变量
- 有没有办法在 c++ 中制作类型变量?
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 如何检查类中定义的枚举类型变量是否被分配给?
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 是否可以在没有结构的情况下创建新的类型变量?
- 为什么类型变量;不调用默认 CTR
- 如何使用CIN将输入整数值获取到char类型变量中
- 如何为 char** 类型变量提供适当的值,以便将其分配给字符串变量
- 在C++标准中哪里说必须初始化 const 内置类型变量的定义
- 为什么可以将其他类型变量用作C 中常量参考参数参数的参数
- Eclipse CDT 打开声明的自动类型变量
- 如何计算长长类型变量中的位数
- 将自动类型变量初始化为零.这种类型安全吗?