模板名称空间和typedef是非法的 - 变通办法?

时间:2009-04-15 20:30:38

标签: c++ function templates namespaces typedef

我有一个模板化函数fct,它使用一些基于模板参数的复杂数据结构。它还调用一些独立的helpers命名空间中的辅助函数(模板化为同一类型),并使用相同的复杂数据结构。现在它变得非常难看,因为我们无法为所有函数都可以访问的复杂类型创建一个typedef

namespace helpers {
  template<class T>
  void h1(const std::vector< std::vector< std::map<T, std::set<T> > > >& bar){
    // ...
  }
}

template<class T>
void fct(const std::vector< std::vector< std::map<T, std::set<T> > > >& bar){
  // ...
  helpers::h1(bar);
}

现在我想通过使用一个所有函数都可以使用的typedef来使它更漂亮。

模板typedef会很好,但不允许:

template<class T> 
typedef std::vector< std::vector< std::map<T, std::set<T> > > > Bar;

我认为另一个解决方案是将所有这些函数包装在一个模板namespace中,但在C ++中也不允许这样做(我听说它将在`C ++ 0x'...中)。

我们当然有模板化的类,但请注意,我并不真的希望用户必须构造一个对象并在其上调用成员函数。所以我最终使用的解决方法是使用模板化的类,其中所有成员函数都是static

template<class T>
class All {

  typedef std::vector< std::vector< std::map<T, std::set<T> > > > Bar;

  static void fct(const Bar& bar){
    // ...
    h1(bar);
  }

private:
  static void h1(const Bar& bar){
    // ...
  }
};

我的问题是:如果我的代码的大部分内容都像那样组织,那可能会有点滑稽?毕竟有很多只有静态成员函数的类有点不寻常吗?是否有其他解决方案/解决方法可以使“模板化typedef”/“模板化命名空间”成为可能?

2 个答案:

答案 0 :(得分:8)

  

是否有其他解决方案/解决方法可以使“模板化typedef”/“模板化命名空间”成为可能?

GOTW #79: Template Typedef

The New C++ Typedef Templates(参见第1节:问题和当前的解决方法)

答案 1 :(得分:0)

对于在后C ++ 11世界中阅读此问题的任何人:使用C ++ 11, 是模板typedef,它被称为`using& #39; (它实际上可以完全取代typedef。在问题的上下文中,这就是我们所做的:

template<class T> 
using Bar = std::vector< std::vector< std::map<T, std::set<T> > > >;

namespace helpers {
template<class T>
void h1(const Bar<T>& bar){
    // ...
}
}

template<class T>
void fct(const Bar<T>& bar){
  // ...
  helpers::h1(bar);
}

美好而简单。排序。