【发布时间】:2020-12-07 23:14:49
【问题描述】:
我正在尝试专门化一个模板来处理主要类型、模板类型和专用/别名模板类型。请参阅下面的代码示例。
它编译但不链接。
如何为zero() 编写一个模板特化,我可以调用为zero<myvec>() 并且仍然可以调用zero<double> 等?
原因是在我的应用程序中,我没有给出myvec 的大小N,所以我不能写zero<vec_t, N>(),但是,我知道myvec 是一个模板别名,如下所示,我知道模板的结构等,而不是大小:
#include <iostream>
#include <array>
#include <vector>
template<std::size_t N>
using vec_t = std::array<double, N>;
using v_t = std::vector<double>;
using v5_t = vec_t<5>;
// generic declaration
template<typename T> T zero();
// full specialization to double
template<> double zero() { std::cout << " -> Double\n"; return 0;}
// full specialization to v_t
template<> v_t zero() { std::cout << " -> vector<double>\n"; return v_t{}; };
// full specialization to v5_t
template<> v5_t zero() { std::cout << " -> vec_t<5>\n"; return v5_t{}; };
// attempt at partial specialization to vec_t<N>
template<template<typename T, std::size_t N> typename V, typename T, std::size_t N> V<T, N> zero() {
std::cout << " -> V<T, N>\n";
return V<T, N>{};
};
template<template<std::size_t N> typename V, std::size_t N> V<N> zero() {
std::cout << " -> V<N>\n";
return V<N>{};
};
int main() {
double z1 = zero<double>(); // works
v_t z2 = zero<v_t>(); // works
v5_t z3 = zero<v5_t>(); // works
const std::size_t N = 6;
vec_t<N> z4 = zero<std::array, double, N >(); // works, but requires full specs of vec_t
vec_t<N> z5 = zero<vec_t, N>(); // works, but requires N
using myvec = vec_t<6>;
myvec z6 = zero<myvec>(); // linker error ! but is what I'd like to write
return 0;
}
你可以看看CompilerExplorer。
非常感谢您的帮助! (P.S. 最高 Cpp17 的解决方案都可以)
【问题讨论】:
标签: c++ templates c++17 template-meta-programming template-specialization