有没有办法在 c++ 中制作类型变量?

Is there a way to make a type variable in c++?

本文关键字:类型变量 c++ 有没有      更新时间:2023-10-16

我很好奇一种制作类型变量的方法。 我的意思在下面的代码中解释:

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内部做一些神奇的事情。