Vla*_*eru 2 c++ templates namespaces class function-templates
我有类似的东西
template <typename T>
T func1() { /* ... */ }
template <typename T>
T func2() { /* ... */ }
// many other functions which use the same template line
Run Code Online (Sandbox Code Playgroud)
如果我试试这个
template <typename T>
T func1() { /* ... */ }
T func2() { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
我得到编译错误.
是否有可能只编写template
一次部件并使代码工作?
不,在C++中你不能这样做(你可以使用D编程语言),而不是
namespace detail {
template<class T> func1() { /* */ }
template<class T> func2() { /* */ }
}
Run Code Online (Sandbox Code Playgroud)
您可以使用
template<class T>
struct detail
{
static T func1() { /* */ }
static T func2() { /* */ }
};
Run Code Online (Sandbox Code Playgroud)
如果您想同时和部分地专门化所有功能(您不能部分专门化功能模板,但您可以使用类模板),这将变得更有利.
注意:有一个缺点:命名空间对新函数是开放的,但是类不是,除非你控制它们的源,所以你最好确定要组合在一起的内容.