有没有办法为函数模板特化命名一个类型?

时间:2014-04-28 18:48:59

标签: c++ templates c++11

例如,当我们有一个通用函数模板时,我们可以在函数中使用模板类型:

template <typename T>
void foo()
{
  T t;
  ...
}

现在,想象一下这个函数模板的特化:

template <>
void foo<MySpecialType>()
{
  T t; // Does not compile, no knowledge of formal template argument T
  MySpecialType t2; // This is OK, but I have to mention MySpecialType again
}

template <>
void foo<MySpecialType2>()
{
  T t; // Does not compile, no knowledge of formal template argument T
  MySpecialType2 t2; // This is OK, but I have to mention MySpecialType2 again
}

请注意,在上面的两个特化中,我必须提到函数体内名称专用的模板参数的类型。我宁愿使用更通用的占位符(即T),而不是在函数模板特化的主体内重复专门的类型(可能是多次)。

如果有办法在实际的专业化功能定义中使用T或创建别名,那就太棒了。我知道我可以通过实际函数体内的类型别名来做到这一点:

template<>
void foo<MySpecialType>
{
  using T=MySpecialType; // But then I still repeat the type at least once
  ...

我更喜欢专业化惯例,如:

// Warning: Not valid C++
template<>
void foo<T=MySpecialType>
{
  T t;
  ...

或者:

// Warning: Not valid C++
template<T>
void foo<MySpecialType>
{
  T t;
  ...

感谢您的任何建议。

2 个答案:

答案 0 :(得分:2)

您可以这样做:

template <typename T>
struct bar
{
    using Type = T;

    static void foo();
};

template <typename T>
void bar<T>::foo()
{
    Type t;
    // ...
}

template <>
void bar<MySpecialType>::foo()
{
    Type t;
    // ...
}

template <>
void bar<MySpecialType2>::foo()
{
    Type t;
    // ...
}

template <typename T>
void foo()
{
    bar<T>::foo();
}

但你真的需要吗?

答案 1 :(得分:0)

这是可行的。以下是一个使用部分特化的工作解决方案,以及包含静态函数的类模板:

template<typename T, typename U = void>
struct foo_impl
{
    static void bar()
    {
        ::std::cout << "T\n";
    }
};

template<typename T>
struct foo_impl<T, typename ::std::enable_if<::std::is_same<T, int>::value>::type>
{
    static void bar()
    {
        ::std::cout << "int\n";
    }
};

template<typename T>
void foo()
{
    foo_impl<T>::bar();
}