C++11 如何使用“模板”实现模板化功能;“子模板”;
我有一个函数,声明是C++11 如何使用“模板”实现模板化功能;“子模板”;,c++11,c++14,C++11,C++14,我有一个函数,声明是 template<typename T> T get(int x); 模板T get(int x); 我想要实现的是实现一个返回类型为模板类的版本(又称chrono::time_point) 我试过了 template<typename clock> std::chrono::time_point<clock> get(int x) { // implementation } template std::chrono::time
template<typename T> T get(int x);
模板T get(int x);
我想要实现的是实现一个返回类型为模板类的版本(又称chrono::time_point)
我试过了
template<typename clock> std::chrono::time_point<clock> get(int x) {
// implementation
}
template std::chrono::time\u point get(int x){
//实施
}
但这与声明不符。正确的方法是什么?不能部分地专门化函数 但是,您可以通过traits/function对象类来路由函数模板,以执行您想要的操作
namespace details {
template<class T>
struct get {
T operator()(int x) {
// code
}
};
template<class clock>
struct get<std::chrono::time_point<clock>> {
using T = std::chrono::time_point<clock>;
T operator()(int x) {
// code
}
};
}
template<class T> T get(int x) {
return details::get<T>{}(x);
}
名称空间详细信息{
模板
结构获取{
T运算符()(int x){
//代码
}
};
模板
结构获取{
使用T=std::chrono::time_点;
T运算符()(int x){
//代码
}
};
}
模板T获取(int x){
返回详细信息::get{}(x);
}
从C++11开始,模板函数不能部分专用化。我怀疑它们也能在C++14中使用。