c++ - 我可以使用 decltype() 来避免显式模板实例化中的代码重复吗?

标签 c++ templates code-duplication decltype explicit-instantiation

我有一个很长的模板函数声明:

template <typename T> void foo(lots ofargs, goin here, andeven more, ofthese arguments, they just, dont stop);

没有重载。我想显式实例化它。我可以写(比如 T = int):

template void foo<int>(lots ofargs, goin here, andeven more, ofthese arguments, they just, dont stop);

但我真的不想复制那么长的声明。我希望喜欢能够说出类似的话:

template <typename T> using bar = decltype(foo<T>);

然后:

template bar<int>;

现在,第一行编译(GCC 4.9.3),但第二行没有。我能让它以某种方式工作吗?或者我可以使用 decltype() 一些其他方式来避免复制实例化的声明吗?

注意:我特意使用了一个示例,在该示例中您不能仅从参数推断出类型,因为我希望任何解决方案也支持这种情况。

最佳答案

当然。来自 [temp.explicit]:

The syntax for explicit instantiation is:
    explicit-instantiation:
        externopt template declaration

[...] If the explicit instantiation is for a function or member function, the unqualified-id in the declaration shall be either a template-id or, where all template arguments can be deduced, a template-name or operator-function-id. [ Note: The declaration may declare a qualified-id, in which case the unqualified-id of the qualified-id must be a template-id. —end note ]

我们需要一份声明。假设我们从:

template <class T> void foo(T ) { }

我们可以通过以下方式显式专门化:

template void foo<char>(char );   // template-id
template void foo(int );          // or just template-name, if the types can be deduced

这和写的一样:

using Fc = void(char );
using Fi = void(int );

template Fc foo<char>;
template Fi foo;

这等同于写:

template <class T> using F = decltype(foo<T> );

template F<char> foo<char>;
template F<int> foo;

基本上,template bar<int> 的原因不起作用是因为它不是声明。你也需要这个名字。

关于c++ - 我可以使用 decltype() 来避免显式模板实例化中的代码重复吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558915/

相关文章:

c++ - #定义一个模板方法

c++ - 没有函数模板的实例与参数列表匹配(试图打印数组)

c++ - 构造函数中模板化类成员的继承

c++ - 避免 const 和非常量成员函数中的代码重复

java - 如何以更少的代码重复将关卡添加到我的游戏中?

c++ - 我的弹射器游戏产生的距离不正确

c++ - 如何在 C++ 中使用通用引用参数为模板类编写构造函数

c++ - 使用 streamhtmlparser 的例子

c++ - 在不损失性能的情况下提高代码可读性

c# - 如何清理此代码以消除重复?