我有类似的东西
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
部分并使代码运行?
最佳答案
不,在 C++ 中你不能这样做(但是在 D 编程语言中你可以),但是
namespace detail {
template<class T> func1() { /* */ }
template<class T> func2() { /* */ }
}
你可以使用
template<class T>
struct detail
{
static T func1() { /* */ }
static T func2() { /* */ }
};
如果你想同时和部分特化所有函数(你不能部分特化函数模板,但你可以为类模板),这将变得有利。
注意:有一个缺点: namespace 对新功能开放,但类不是,除非您控制它们的来源,因此您最好确定将什么组合在一起。
关于c++ - 使用相同的模板实现更多功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25162076/