【问题标题】:how to get template parameter of a template template parameter?如何获取模板模板参数的模板参数?
【发布时间】:2017-07-25 13:41:39
【问题描述】:

假设std::vector 没有value_type。是否可以编写一个模板来推断value_type?或者更笼统地说,给定T<X>,我如何推断X

一个很幼稚的..

template <template <typename X> T>
void test(T<X> t) { 
     X x;
}

可能会让对模板有一点了解的人嘲笑我的愚蠢尝试,当像这样实例化时:

int main() {
    std::vector<int> x;
    test(x);
}

产生以下错误:

error: expected ‘class’ before ‘T’
 template < template<typename X> T>
                                 ^
error: ‘X’ was not declared in this scope
 void test(T<X> u) {
             ^
error: template argument 1 is invalid
 void test(T<X> u) {
              ^
In function ‘void test(int)’:
error: ‘X’ was not declared in this scope
   X x;
   ^
error: expected ‘;’ before ‘x’
   X x;
     ^
In function ‘int main()’:
error: no matching function for call to ‘test(std::vector<int>&)’
   test(x);
         ^
note: candidate is:
note: template<template<class X> class T> void test(int)
 void test(T<X> u) {
      ^
note:   template argument deduction/substitution failed:
note:   cannot convert ‘x’ (type ‘std::vector<int>’) to type ‘int’

编辑:第一个很容易修复,但修复它不会影响其他...

PS:我想我有一个小误解,因为std::vector&lt;int&gt; 不是模板,而是具体类型。但是,我仍然想知道是否有办法通过一些模板魔法从someTemplate&lt;int&gt; 获取int

【问题讨论】:

  • 如果我没记错的话,你必须使用 class 和嵌套模板。类似template &lt;template &lt;typename X&gt; class T&gt;.
  • 请注意,std::vector 有第二个(默认)模板参数。
  • 一种解决方法,但如果您只是使用容器,您可以获取一个迭代器并使用std::iterator_traits

标签: c++ templates c++98


【解决方案1】:

您可以创建一个特征来提取这些参数:

template <typename T> struct first_param;

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

对于 C++11 之前的版本,您必须处理参数数量直到可接受的值:

template <typename T> struct first_param;

template <template <typename> class C, typename T>
struct first_param<C<T>>
{
    typedef T type;
};

template <template <typename, typename> class C, typename T, typename T2>
struct first_param<C<T, T2>>
{
    typedef T type;
};

template <template <typename, typename, typename> class C,
          typename T, typename T2, typename T3>
struct first_param<C<T, T2, T3>>
{
    typedef T type;
};

// ...

【讨论】:

  • 看起来像 c++11 或更高版本,如果我在问题中没有明确表示抱歉。
  • @tobi303:添加了 C++03 版本。
  • 我很幸运,我所追求的具体案例只有一个参数。感谢您的回答。看到所有...using 我担心 C++03 解决方案将是一个可怕的 hack,但该解决方案看起来非常好和简单
  • 刚刚收到了关于这个问题的 ping 信息,很惊讶我当时知道的这么少。我知道是题外话,不过我觉得还是要适当滴个大大 谢谢!这里是我在 SO 期间深入研究 C++ 的有趣内容时获得的所有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 2014-04-12
相关资源
最近更新 更多