【问题标题】:Use the same template for more functions使用相同模板获得更多功能
【发布时间】:2014-08-06 13:47:09
【问题描述】:

我有类似的东西

template <typename T>
    T func1() { /* ... */ }
template <typename T>
    T func2() { /* ... */ }
// many other functions which use the same template line

如果我试试这个

template <typename T>
    T func1() { /* ... */ }
    T func2() { /* ... */ }

我得到编译错误。

是否有可能只编写一次template 部分并使代码工作?

【问题讨论】:

  • 您可以将这些函数包装到结构或类中
  • 第二种情况:unknown type name T 代表func2。可能是因为它只识别第一个函数的模板。

标签: c++ class templates namespaces function-templates


【解决方案1】:

不,在 C++ 中你不能这样做(但是你可以在 D 编程语言中),而是用

namespace detail {
    template<class T> func1() { /* */ }
    template<class T> func2() { /* */ }        
}

你可以使用

template<class T>
struct detail
{
    static T func1() { /* */ }
    static T func2() { /* */ }    
};

如果您想同时和部分特化所有函数,这将变得有利(您不能部分特化函数模板,但可以用于类模板)。

注意:有一个缺点:命名空间对新功能开放,但类不开放,除非您控制它们的来源,因此您最好确定要组合在一起的内容。

【讨论】:

  • 完美运行,这是一个完整的答案。非常感谢!
  • @Vlad 很高兴能帮上忙!
【解决方案2】:

如果您担心必须多次重复模板参数声明,您可以将函数包装到模板结构或类中

例如

template <typename T> struct Wrapper {
    static T func1() { /* ... */ }
    static T func2() { /* ... */ }
};

【讨论】:

    【解决方案3】:

    如果你不能改变你的函数签名,你可以做一个define来做到这一点:

    #define Templated_T template<class T> T
    Templated_T func1() { /* ... */ }
    Templated_T func2() { /* ... */ }
    

    它不是很 C++-ish,但应该可以正常工作。

    【讨论】:

    • 现在尝试将 T 重构为 U。至少,使用宏参数
    • @TemplateRex 重命名 T info U 有什么意义?更有可能的是,需要更改“func1”签名/返回类型。如果是包装器,它会更复杂。
    • 首先,宏几乎不比直接写出来少打字。此外,在宏内部使用返回类型也不是一个好主意,如果你想添加另一个函数template&lt;class T&gt; void func3() 那就行不通了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2017-07-08
    相关资源
    最近更新 更多