c ++模板专业化参数重复

时间:2018-05-18 19:29:10

标签: c++ c++11 templates

最近我注意到模板特化的以下问题。

请注意,如果f具有以下特殊性,则模板参数名称可以是非常长的类型,可能来自其他模板。

template <class T> void f(T t) {}

template <>
void f<VeryLongType>(VeryLongType t)
{
    using T = VeryLongType;
    // ...
}

请注意,这个非常长的类型名称重复3次。此外,如果f返回此类型的值,则会引入另一个重复项(auto  将是一种解决方法)。

我想知道是否存在一些简化的语法,以便不需要重复?

也许如下:

template <>
void f<T = VeryLongType>(T t)
{
   // ...
}

1 个答案:

答案 0 :(得分:5)

您实际上并不需要明确指定特化类型,例如:

template <>
void f(VeryLongType t)
{
    using T = VeryLongType;
    // ...
}

很好。如果decltype(t)非常长,则可以使用VeryLongType缩短类型别名...

using T = decltype(t); // makes it more generic too
相关问题