gpt4 book ai didi

C++,模板 : get type of the item

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:17 25 4
gpt4 key购买 nike

有两种结构:

template <typename T>
struct AB
{
T a, b;

AB <T> ( ) : a ( 0.0 ), b ( 0.0 ) {}
};


template <typename T>
struct ABList
{
typedef std::list < AB <T> > Type;
typedef T Type2;
};

还有一个函数

template <typename List>
void test ( List l )
{
List::iterator i_l = l.begin();

//Here *i_l type is needed instead of double
double val = (*il).a;

}

有什么方法可以得到 *i_l 模板化类型(这里是 double ),即

std::list::Item type

不传递任何其他参数 if

int main(int argc, char* argv[])
{
ABList <double> ::Type intervals;

test (intervals);


return 0;
}

感谢您的帮助,C++ 03 是首选。

更新问题

如果是模板化类型

std::list::Item type

表示test()的一个形参,本解法

template <typename List>
void test ( List l, typename List::value_type::value_type val )
{
...
}

int main(int argc, char* argv[])
{
ABList <double> ::Type intervals;
double x = 7.0;

test <ABList<double>> (intervals, x);

return 0;
}

不起作用...出现以下错误:

error C2770: invalid explicit template argument(s)

版本

test (intervals, x);

导致另一个错误:

Failed to specialize function template 'void test(List,List::value_type::{ctor})'

最佳答案

在 C++11 中,只需使用 auto :

auto val = (*il).a;

如果你以后需要引用那个类型,你可以使用decltype(val) .

在 C++03 中,您可以获得标准容器类型的基础类型 L作为:

L::value_type

所以在你的情况下应该是:

typename List::value_type

然而,在你的情况下,这会给你类型 AB , 而不是 AB::a 的类型.如果您需要能够在编译时检索类型 T对于 AB 的实例模板,您需要在 AB 中提供一些类型别名.例如:

template <typename T>
struct AB
{
typedef T value_type;
// ^^^^^^^^^^^^^^^^^^^^^

T a, b;

AB <T> ( ) : a ( 0.0 ), b ( 0.0 ) {}
};

然后你可以这样做:

typename List::value_type::value_type val = (*il).a;

如果你不想改变 AB 的定义正是出于这个目的,您可以定义一个单独的类型特征,例如:

template<typename T>
struct underlying_type_of;

template<typename T>
struct underlying_type_of<AB<T>>
{
typedef T type;
};

然后您可以获得基础类型 TAB<T>如下图:

typename underlying_type_of<typename List::value_type>::type val = (*i_l).a;

关于C++,模板 : get type of the item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16421822/

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