我可以实例化一个模板而不重复其签名吗
Can I instantiate a template without repeating its signature?
我想实例化一些具有长签名的函数:
template<typename T> void foo(
T& t,
SomeType some_parameter,
AnotherType another_parameter,
EtcType yet_another_parameter,
AsYouCanTell this_is_a_very_long_signature);
实例化foo
的简单方法是:
template void foo<int>(
int& t,
SomeType some_parameter,
AnotherType another_parameter,
EtcType yet_another_parameter,
AsYouCanTell this_is_a_very_long_signature);
但这是长签名的重复。如果我想要5种不同类型的特定实例化,我会复制5次吗?没有道理。。。
我在想也许我可以写
template decltype(foo<int>);
但由于某种原因,这不起作用。不知怎么的,我能让它工作吗?
实际上,您可以在不重复其签名的情况下实例化函数,但语法有点不同:
template
decltype(foo<int>) foo<int>;
decltype
为您提供了类型,但显式实例化需要声明(这是一个后跟名称的类型)。
尝试使用GCC 4.9.1;它按预期工作,并且即使使用CCD_ 3标志也在没有任何警告的情况下编译。
它实际上比@5gon12der建议的更简单:
template decltype(foo<int>) foo;
但是,是的,就像他说的那样——decltype()
只提供类型,签名并不是真正的类型。
编辑:当模板有值参数而不仅仅是类型时,这是不起作用的,所以如果我们有
template <typename T, unsigned Val> bar(T t);
然后
template decltype(bar<int, 1>) bar;
不会编译,而
template decltype(bar<int, 1>) bar<int, 1>;
意志。
我认为这是一个很好的、合法的宏用途:
#define INSTANTIATE_FOO(type)
template void foo<type>(type& t,
SomeType some_parameter,
AnotherType another_parameter,
EtcType yet_another_parameter,
AsYouCanTell this_is_a_very_long_signature);
INSTANTIATE_FOO(int)
INSTANTIATE_FOO(float)
INSTANTIATE_FOO(my_little_dragon)
#undef INSTANTIATE_FOO
否,因为过载
template<typename T> void foo(T& t,
SomeType some_parameter,
AnotherType another_parameter,
EtcType yet_another_parameter,
AsYouCanTell this_is_a_very_long_signature);
template<template T> void foo(T& t); //completely unrelated function
template<template T> void foo(char); //another completely unrelated function
现在想象一下,显式实例化第一个所需的最小信息是什么?好吧,你需要完整的签名来消除歧义,所以
explicit int foo(int&, SomeType, AnotherType, EtcType, AsYouCanTell)
是理论上的最小信息量。因此,C++所需的开销实际上很小:
template void foo<int>(int& t, SomeType, AnotherType, EtcType, AsYouCanTell);
如果你不想键入所有这些,那么Konrad关于宏的建议就是最好的选择。
相关文章:
- C++ - 使用另一个类的构造函数实例化一个对象
- 即使我正在.cpp文件中实例化一个伪对象,.cpp文件内模板函数的定义也不起作用
- 实例化一个模板类,该类采用具有不同函数签名的构造函数中的函数指针
- 为什么我不能通过执行 "myVector[i].data()" 来实例化一个类,其中 myVector[i].data() 是一个字符串?
- C++/CX - 我需要从常量字符*实例化一个平台::字符串
- 在CNI/C++代码中实例化一个模板类
- Linux gcc picking试图在函数所在的位置实例化一个模板
- 我可以实例化一个模板而不重复其签名吗
- 用类似Java的c++实例化一个抽象类
- 如何在C++中强制在另一个对象(依赖于它)中实例化一个对象
- 实例化一个二维向量,其中一组对作为单元值
- 用C++实例化一个新对象
- 在堆栈上实例化一个类,其中 var 在标头中定义
- c++模板函数:显式实例化一个或多个专门化
- 在cpp中实例化一个新对象
- 如何在c++ dll中实例化一个类,使它在函数调用之间保持内存
- 如何实例化一个只知道其名称的对象
- 实例化一个不使用变量的ifstream对象
- 我怎么能使用一个非常量值实例化一个类的多个对象
- 在c++的另一个类的构造函数中实例化一个类的对象