获取模板参数的decltype

Ger*_*ard 5 c++ templates decltype

我经常想得到一个类模板参数的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)>();
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法获得模板参数的decltype而不做这个hack?如果没有,获得这样一个值的decltype的最佳解决方法是什么?

Jar*_*d42 8

您可以创建一个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;
};
Run Code Online (Sandbox Code Playgroud)

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

typename get_template_type<C>::type
Run Code Online (Sandbox Code Playgroud)

实例

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

template <template <typename > class C, typename T, typename ... Ts>
struct get_template_type<C<T, Ts...>>
{
    using type = T;
};
Run Code Online (Sandbox Code Playgroud)