gpt4 book ai didi

c++ - 获取模板参数的 decltype

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:31 27 4
gpt4 key购买 nike

我经常想要获取类模板参数的 decltype 以便进一步使用它,就像在我已经剥离和简化以显示我的问题的循环中:

template <typename T>
class Foo {
public:
T type; //This is my hack to get decltype of T
};

template <typename T>
class Bar {
public:

};

int main() {
for(auto& foo : fs) {
//Is there some way to get the decltype of the template without having to refer to some arbitrary T member of Foo?
auto bar = someFunction<decltype(foo.type)>();
}
}

有没有办法在不执行此 hack 的情况下获取模板参数的 decltype?如果不是,获得此类值的 decltype 的最佳解决方法是什么?

最佳答案

您可以创建一个 type_traits:

template <typename C>
struct get_template_type;

template <template <typename > class C, typename T>
struct get_template_type<C<T>>
{
using type = T;
};

然后你使用它(假设 C = Foo<T> ,你将有 T )

typename get_template_type<C>::type

Live example

编辑:对于具有多个模板参数的类,检索第一个:

template <template <typename > class C, typename T, typename ... Ts>
struct get_template_type<C<T, Ts...>>
{
using type = T;
};

关于c++ - 获取模板参数的 decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27382432/

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