gpt4 book ai didi

c++ - 获取模板参数的 typedef,或者失败,获取类型本身

转载 作者:太空狗 更新时间:2023-10-29 19:40:38 25 4
gpt4 key购买 nike

我试图从我定义的类(ValueType typedef)中获取 typedef 指向的类型。但是,当失败时,我希望它返回给定的类型(例如,如果我给它一个 double,我希望它返回一个 double)。这是我目前所拥有的:

struct myClass { typedef double ValueType; };

template < typename V, typename U = typename V::ValueType>
struct base_type { typedef U type; };
template < typename V >
struct base_type< V, V > { typedef V type; };

static_assert( std::is_same < typename base_type< myClass >::type , double >::value,
"base_type doesn't work" ); //This works.
static_assert( std::is_same < typename base_type< double >::type , double >::value,
"base_type doesn't work" ); //This returns "error: 'double' is not a class, struct, or union type"

但是,这不起作用,第二个 static_assert 失败了。显然,第二个定义从未被调用,但我不确定为什么(它肯定比第一个匹配得更好)。

有什么想法吗?

最佳答案

或者

template < typename V, typename = void>
struct base_type { typedef V type; };
template < typename V >
struct base_type< V,
typename base_type<void, typename V::ValueType>::type > {
typedef typename V::ValueType type;
};

我们多么喜欢这些粗鲁丑陋的 SFINAE hacks :)

关于c++ - 获取模板参数的 typedef,或者失败,获取类型本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15393093/

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