我可以实例化一个模板而不重复其签名吗

Can I instantiate a template without repeating its signature?

本文关键字:实例化 一个 我可以      更新时间:2023-10-16

我想实例化一些具有长签名的函数:

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关于宏的建议就是最好的选择。