【问题标题】:Can I use decltype() to avoid code duplication in explicit template instantiations?我可以使用 decltype() 来避免显式模板实例化中的代码重复吗?
【发布时间】:2016-04-11 20:45:33
【问题描述】:

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

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() 其他方式来避免复制实例化声明吗?

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

【问题讨论】:

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


    【解决方案1】:

    当然。来自 [temp.explicit]:

    显式实例化的语法是:
    显式实例化
    externopttemplate 声明

    [...] 如果显式实例化是针对函数或成员函数,则声明中的 unqualified-id 应为 template-id 或,其中可以推导出所有模板参数,a 模板名称操作员功能ID[注:声明可以声明一个qualified-id,在这种情况下 qualified-idunqualified-id 必须是 template-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&lt;int&gt; 不起作用的原因是它不是声明。你也需要名字。

    【讨论】:

    • 我正在编辑这个问题,以确保你不能推断出函数参数的模板参数,这是我真正感兴趣的。我只是撒了一个 T t 来衡量,并不是要您使用它...如果您的答案仍然相关,那就太好了。
    • @einpoklum 从这个问题上看不太清楚,为什么你认为我的回答不相关?
    • 我并不是说这无关紧要,我只是感觉(在您上次编辑之前)您可能比实际更依赖它。
    猜你喜欢
    • 2017-09-12
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多