假设我们需要一个函数模板,它应该根据类型返回一个整数:
template<typename T>
int get_type();
此外,我们确实将其专门用于几种类型:
template<>
int get_type<int>()
{
return TYPE_INT;
}
// And so on for other types...
这很好用,但不适用于数组类型。我可以执行以下操作:
template<>
int get_type<char[]>()
{
return TYPE_STRING;
}
并且编译器“同意”这一点,但链接器不同意。因为类型
char[]
例如,与 char[5]
不同。 .有没有什么方法可以在没有函数参数的情况下实现这个函数模板?即,我知道我们可以这样做:
template<typename T>
int get_type(const T&);
但是,实际上这里不需要(使用)函数参数。
编辑:
我使用 C++ 11。
最佳答案
您不能部分专门化模板函数(但您可以用于模板类)
另一种方法是使用重载进行标签调度,而不是专门化:
template <typename> struct Tag{};
constexpr int get_type(Tag<int>) { return TYPE_INT; }
template <std::size_t N>
constexpr int get_type(Tag<char[N]>) { return TYPE_STRING; }
template <typename T>
constexpr int get_type() { return get_type(Tag<T>{}); }
关于c++ - 有没有办法通过数组类型专门化函数模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61246142/