如果模板类型是另一个模板,则运行代码

时间:2013-07-06 14:44:52

标签: c++ templates c++11

如何在C ++中执行此操作?缺少static_if将使其变得更难。

template<typename T>
struct foo {
  foo() {
    //construction

    //if (T is an instantiation of some other template, say std::vector)
    //{
    //   stuff 1
    //}
  }

  void some_func() {
    //some code

    //if (T is an instantiation of some other template, say std::vector)
    //{
    //   stuff 2
    //}
  }
};

如果有任何帮助,这里的代码告诉我们T是否是另一个模板:

Doing a static_assert that a template type is another template

唯一的问题是如何将其翻译成“if”条件。

2 个答案:

答案 0 :(得分:2)

使用调度助手函数:

template<typename T>
struct foo {
public:
  foo() {
    //construction

    stuff1(static_cast<T*>(nullptr));
  }

  void some_func() {
    //some code

    stuff2(static_cast<T*>(nullptr));    
  }

private:
  template<typename U> void stuff1(U*) {}
  template<typename E, typename A> void stuff1(std::vector<E,A>*)
  { /* stuff 1 */ }

  template<typename U> void stuff2(U*) {}
  template<typename E, typename A> void stuff2(std::vector<E,A>*)
  { /* stuff 2 */ }
};

答案 1 :(得分:0)

您指向的链接已经有一个条件代码,可以告诉您正确的答案。你所要做的就是将它放在“if”中。

不需要“static_if”。如果您的代码在编译时可以确定是否采用了if,则优化输出未采用的路径,以及实际的if语句。由于模板函数是针对每种类型单独实例化(读取 - 编译)的,因为对于每个实例化,if条件都可以静态检测,只需使用标准if。

Shachar