在模板化类中使用模板化函数的困难

Difficulties with templated functions in templated classes

本文关键字:函数      更新时间:2023-10-16

我遇到了一个问题,而试图编写递归模板成员函数通过元组迭代。

在以下代码中:

#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)

谢谢,

注:请不要取笑我的简化测试用例。产生这个场景的项目比这个例子更令人印象深刻……

__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删除)。