模板化类中模板化函数的困难

时间:2011-10-11 03:00:57

标签: c++ templates c++11

在尝试编写递归模板成员函数以迭代元组时,我遇到了一个问题。

在以下代码中:

#include <cstddef>
#include <iostream>
#include <string>
#include <tuple>

template <typename... P>
class A
{
public:
  typedef std::tuple<P...> tup_t;

  tup_t tup;
};

template <typename T, typename... P>
class AA : public A<P...>
{
public:
  T junk;
};

template <typename T>
class B
{
public:
  T a;

  void func(const char* delim);

private:
  template <size_t x>
  void __func(const char* delim);
};

template <typename T>
void B<T>::func(const char* delim)
{
  __func<std::tuple_size<typename T::tup_t>::value>(delim);
}

template <typename T>
template <size_t x>
typename std::enable_if<(x > 1), void>::type
B<T>::__func(const char* delim)
{
  std::cout << std::get<x-1>(a.tup) << delim;

  __func<x-1>(delim);
}

template <typename T>
template <size_t x>
typename std::enable_if<(x == 1), void>::type
B<T>::__func(const char* delim)
{
  std::cout << std::get<x-1>(a.tup) << std::endl;
}

int main()
{
  typedef A<int,float,std::string> T_first;
  B<T_first> b;

  std::get<0>(b.a.tup) = 5;
  std::get<1>(b.a.tup) = 4.0;
  std::get<2>(b.a.tup) = "string";

  b.func(" - ");

  typedef AA<int,std::string,double,size_t> T_second;
  B<T_second> bb;

  std::get<0>(bb.a.tup) = "test";
  std::get<1>(bb.a.tup) = 3.0;
  std::get<2>(bb.a.tup) = std::tuple_size<T_second::tup_t>::value;

  bb.func(" => ");

  return 0;
}

当我编译:

$ g++-4.5 -std=c++0x -W -Wall -pedantic-errors test6.cpp

我收到以下错误:

test6.cpp:60:1: error: prototype for ‘typename std::enable_if<(x > 1), void>::type B<T>::__func(const char*)’ does not match any in class ‘B<T>’
test6.cpp:31:32: error: candidate is: template<class T> template<unsigned int x> void B::__func(const char*)
test6.cpp:70:1: error: prototype for ‘typename std::enable_if<(x == 1), void>::type B<T>::__func(const char*)’ does not match any in class ‘B<T>’
test6.cpp:31:32: error: candidate is: template<class T> template<unsigned int x> void B::__func(const char*)

现在,如果我在类中定义B<T>::__func,如:

  template <size_t x>
  typename std::enable_if<(x > 1), void>::type
  __func(const char* delim)
  {
    std::cout << std::get<x-1>(a.tup) << delim;

    __func<x-1>(delim);
  }

  template <size_t x>
  typename std::enable_if<(x == 1), void>::type
  __func(const char* delim)
  {
    std::cout << std::get<x-1>(a.tup) << delim;
  }

它汇编得很好。

我真的不喜欢在类声明中实现这些功能,所以如果有人可以指出我原来的尝试出错了,我会很感激。

是吗:

template <typename T>
template <size x>

是否应以不同的方式撰写?

编译器版本:gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)

谢谢,

P.S。请不要取笑我的简化测试用例。产生这种情况的项目比这个例子更令人印象深刻......但只是略微。

1 个答案:

答案 0 :(得分:6)

类型必须与__func的声明和定义相匹配。因此,在类定义中,您必须将__func声明为:

template <size_t x>
typename std::enable_if<(x > 1)>::type
__func(const char* delim);

(这相当于使用std::enable_if<(x > 1), void>,因为第二个模板参数默认为void。)

此限制的原因与模板特化有关。事实上,因为您使用的是std::enable_if,所以您依赖于这些专业化,因为std::enable_if<true, T>是一种专业化。另请注意__func<0>不具有返回类型void的情况下的不匹配。它有'返回类型std::enable_if<false, void>::type,它不存在,因此无效(然后通过SFINAE删除)。