C函数模板偏特化?

新手上路,请多包涵

我知道下面的代码是一个类的部分特化:

 template <typename T1, typename T2>
class MyClass {
  …
};

// partial specialization: both template parameters have same type
template <typename T>
class MyClass<T,T> {
  …
};

我也知道 C++ 不允许函数模板部分特化(只允许完整)。但是我的代码是否意味着我已经为一个/相同类型的参数部分专门化了我的函数模板?因为它适用于 Microsoft Visual Studio 2010 Express!如果不是,那么您能否解释一下部分专业化的概念?

 #include <iostream>
using std::cin;
using std::cout;
using std::endl;

template <typename T1, typename T2>
inline T1 max (T1 const& a, T2 const& b)
{
    return a < b ? b : a;
}

template <typename T>
inline T const& max (T const& a, T const& b)
{
    return 10;
}

int main ()
{
    cout << max(4,4.2) << endl;
    cout << max(5,5) << endl;
    int z;
    cin>>z;
}

原文由 Narek 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 484
2 个回答

根据标准,功能部分特化是不允许的。在示例中,您实际上是在 重载而不是专门max<T1,T2> 函数。

如果允许的话,它的 语法 应该 看起来 像下面这样:

 // Partial specialization is not allowed by the spec, though!
template <typename T>
inline T const& max<T,T> (T const& a, T const& b)
{                  ^^^^^ <--- [supposed] specializing here
  return 10;
}

在函数模板的情况下,C++ 标准只允许 完全 化——不包括编译器扩展!

原文由 iammilind 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于迟到的答案,我很抱歉,但我找到了一个解决方案,我在其他答案中没有看到解释(至少不是直接解释)。

函数不能 部分特 化,而类可以。在这里可以做的事情是类内部的静态函数。我们可以让它工作,基本上在类特化中移动“模板部分特化”,并在其中创建标记为静态的函数。这将允许我们通过增加一点所需的代码行来构造我们的部分专用函数。

让我们考虑不可用的部分专用函数 Printer 如下( 根本无法编译的代码)。

 template <class T, class Trait = void>
void Printer(const T&);

template <class T>
void Printer<T, std::enable_if_t<std::is_floating_point_v<T>>>(const T& v){
    std::cout << "I m partially specialized for any floating point type." << std::endl;
}
template <class T>
void Printer<T, std::enable_if_t<std::is_integral_v<T>>>(const T& v){
    std::cout << "I m partially specialized for any integral type." << std::endl;
}

我们可以使用静态类函数并在类上移动部分特化来使其工作,如下所示:

 namespace detail{

    template<class T, class Trait = void>
    struct Specialized;

    template<class T>
    struct Specialized<T, std::enable_if_t<std::is_floating_point_v<T>>>
    {
        static void Printer(const T& v){
            std::cout << "I m specialized for any floating point type"<< std::endl;
        }
    };

    template<class T>
    struct Specialized<T, std::enable_if_t<std::is_integral_v<T>>>
    {
        static void Printer(const T& v){
            std::cout << "I m specialized for any integral type"<< std::endl;
        }
    };
}

template<class T>
void Printer(const T& v)
{
    detail::Specialized<T>::Printer(v);
}

它的结果会更长一些,但会以相对清晰的方式解决我们的问题。您可以在 此处 在 Godbolt 上对其进行测试。

原文由 IkarusDeveloper 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题