简体   繁体   English

C ++ 11中的变量模板专业化

[英]Variadic template specialization in C++11

Is it implemented already, because this does not compile: (using gcc 4.7.2) 它是否已经实现,因为它不能编译:(使用gcc 4.7.2)

template <typename... Ts>
struct Foo {
    int foo() {
        return 0;
    }
};

template <>
struct Foo<int x, int y> {
    int foo() {
        return x * y;
    }
};

int main()
{
    Foo<2, 3> x;
    cout << x.foo() << endl; //should print 6
}

You are making a few mistakes. 你犯了一些错误。 The primary template expects types, not integral constants. 主模板需要类型,而不是整数常量。 You also try to instantiate the template with integral constants, but your partial specialization uses types. 您还尝试使用整数常量实例化模板,但您的部分特化使用类型。

This is closer: 这更接近:

#include <iostream>

template <int... Ts>
struct Foo {
    int foo() {
        return 0;
    }
};

template <>
struct Foo<3, 2> {
  const int x = 3;
  const int y = 2;

  int foo() {
    return x * y;
  }
};

int main()
{
    Foo<2, 3> x;
    std::cout << x.foo() << std::endl; //should print 6
}

But this is not really what we want, right? 但这不是我们想要的,对吗? And it is also clumsy. 它也很笨拙。

#include <iostream>

template<typename Acc, typename... Rest>
struct accum_help; // primary

template<typename Acc, typename F, typename... Rest>
struct accum_help<Acc, F, Rest...> {
  typedef typename accum_help<
    std::integral_constant<typename Acc::value_type, 
                           Acc::value * F::value>, Rest...
    >::type type;
};

template<typename Acc>
struct accum_help<Acc> {
  typedef Acc type;
};

// peek into the first argument to avoid summing empty sequences and
// get the right type
template<typename X, typename... Integrals>
struct accum {
  typedef typename accum_help<
    std::integral_constant<typename X::value_type, 1>, X, Integrals...
    >::type type;
};

int main()
{

  std::cout << accum< std::integral_constant<int, 2>, std::integral_constant<int, 3> >::type::value << std::endl; //should print 6
}

A simpler variant handling only int: 一个更简单的变量只处理int:

template <int...>
struct accum2_help;

template <int Acc, int X, int... Rest> 
struct accum2_help<Acc, X, Rest...> {
  static const int value = accum2_help< Acc * X, Rest...>::value;
};

template <int Acc>
struct accum2_help<Acc> {
  static const int value = Acc;
};

// again don't accept empty packs
template <int T, int... Ts>
struct accum2 {
  static const int value = accum2_help<1, T, Ts...>::value;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM