c++ - 有没有办法为函数模板特化命名类型?

标签 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;
  ...

感谢您的任何建议。

最佳答案

你可以这样做:

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();
}

但你真的需要它吗?

关于c++ - 有没有办法为函数模板特化命名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23348949/

相关文章:

CUDA 中的 C++11 别名模板

c++ - gcc/clang 上的模板错误,但 MSVC 上没有

c++ - 推导类型

c++ - 对引用引用的函数的直观理解

C++ string data() 函数使引用和指针无效?

c++ - 将 NanoGUI 添加到 OpenGL 项目

c++ - 能够将子类实例分配给堆栈框架中的基类变量的动机是什么?

c++ - 让我的程序保持活力的神奇cout

c++ - C++获取构造函数的类型

c++ - C++0x forward_list在不同场景下的表现如何?