我可以使用decltype()来避免显式模板实例化中的代码重复吗
Can I use decltype() to avoid code duplication in explicit template instantiations?
我有一个长模板函数声明:
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()
以其他方式避免复制实例化的声明吗?
注意:我特意使用了一个例子,在这个例子中,您不能仅从参数推断类型,因为我希望任何解决方案也支持这种情况。
当然。来自[显式温度]:
显式实例化的语法为:
nbsp nbsp显式实例化:
nbsp nbsp nbsp nbsp;externopttemplate
声明[…]如果显式实例化是针对函数或成员函数的,则声明中的非限定id应为模板id板名称或运算符函数id[注意:声明可以声明一个限定id,在这种情况下合格id的不合格id必须是模板id-尾注]
我们需要一份声明。让我们假设我们从开始
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++的实体对象?
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 在C++代码中搜索对象的实例化位置
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- 根据运行时参数避免模板实例化的代码重复
- 如何在代码中创建抽象类,让蓝图扩展它,并将该蓝图返回给代码进行实例化?
- 如何在代码中实例化 Vst3 插件?对于 vst3 主机应用
- 生成代码实例化具有不同参数的函数模板
- 如何使用 C++11 unique_ptr实例化我的代码
- 在CNI/C++代码中实例化一个模板类
- 获取在C++中实例化的TCL解释器中执行代码的行号
- 我可以使用decltype()来避免显式模板实例化中的代码重复吗
- 如何在函数调用的一行代码中实例化类
- typedef和显式实例化之间的代码重复
- 用于实例化模板化代码的显式习惯用法 - 不包括其源代码
- 为什么下面的代码会导致模板实例化
- 强制 clang 为类模板实例化的从不引用的静态成员函数发出代码
- C++模板中条件代码实例化的最干净方法
- C++模板函数实例化代码大小
- 编译器:类实例化代码是如何编译的