【问题标题】:Specializing only a part of a template function's implementation仅专门化模板函数实现的一部分
【发布时间】:2012-07-02 20:55:34
【问题描述】:

我想知道如果模板参数之一属于某种类型,是否可以部分专门化模板化方法的行为。

template<class T>
void Foo(T& parameter)
{
    /* some generic - all types - stuff */

    If(T is int) // this is pseudo-code, typeinfo? Boost?
    {
        /* some specific int processing which might not compile with other types */
    }

    /* again some common stuff */
}

欢迎提出任何建议。 谢谢

【问题讨论】:

  • 我编辑了标题,因为“部分专业化”一词的含义与此处所问的完全不同。

标签: c++ templates boost runtime compile-time


【解决方案1】:

如果您只想专门化函数的一部分,那么您只需将函数的一部分分解为专门的实现即可:

template<class T>
void Bar(T &t) {}

void Bar(int &i) {
    /* some specific int processing which might not compile with other types */
}


template<class T>
void Foo(T &t) {
    /* some generic - all types - stuff */

    Bar(t);

    /* again some common stuff */
}

【讨论】:

    【解决方案2】:

    当然:

    // helper funciton
    template <class T>
    void my_helper_function(T& v)
    {
      // nothing specific
    }
    
    void my_helper_function(int& v)
    {
      // int-specific operations
    }
    
    // generic version
    template <class T>
    void Foo(T& v)
    {
      /* some generic - all types - stuff */
    
      my_helper_function(v);
    
      /* again some common stuff */
    }
    

    【讨论】:

    • 重载不是比专门化更好吗?
    • 柔印是对的。为什么要专精?如果你只提供一个int 重载,那就更清楚了。
    【解决方案3】:

    是的,您可以提供模板函数的特化(而不是部分特化)。对于成员函数,您需要在包含模板的类之后的命名空间级别定义特化。

    如果您的意思是应该只对函数的一部分进行专门化,那么您不能直接这样做,但是您可以创建另一个实现该部分逻辑的模板化函数,专门化它并从您的模板中调用它。编译器将使用Foo 模板的单一版本和FooImplDetail 函数的适当版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      相关资源
      最近更新 更多