特定模板类型的功能专用化

Specialization of function for a specific template type

本文关键字:功能 专用 类型      更新时间:2023-10-16

请考虑以下事项:

template <typename TResult> inline TResult _from_string(const string& str);
template <> inline unsigned long long _from_string<unsigned long long>(const string& str) {
    return stoull(str);
}

我可以这样调用该函数:

auto x = _from_string<unsigned long long>("12345");

现在我想为vector s写另一个专业,即:

template <typename T> inline vector<T> _from_string<vector<T>>(const string& str) {
    // stuff that should be done only if the template parameter if a vector of something
}
这样

我就可以做这样的事情:

 auto x = _from_string<vector<int>>("{1,2,3,4,5}");

但是,当我编译函数(在 MSVC 2015 下)时,我收到错误 C2768:"非法使用显式模板参数",这是有道理的,因为我不应该在专用化中使用新的模板参数。

如何重写vector专业化以使其正常工作?

函数模板只能是完全专用的,不能是部分专用的;但类模板可以。

// primary class template
template <typename T>
struct X {
    static T _from_string(const string& str);
};
// full specialization for unsigned long long
template <>
struct X<unsigned long long> {
    static unsigned long long _from_string(const string& str) {
        return stoull(str);
    }
};
// partial specialization for vector<T>
template <typename T>
struct X<vector<T>> {
    static vector<T> _from_string(const string& str) {
        // stuff that should be done only if the template parameter if a vector of something
    }
};
// helper function template
template <typename TResult>
inline TResult _from_string(const string& str) {
    return X<TResult>::_from_string(str);
}

然后

auto x1 = _from_string<unsigned long long>("12345");
auto x2 = _from_string<vector<int>>("{1,2,3,4,5}");

您不能部分专用化功能。

您很少应该完全专注于功能。

处理此问题的更好方法是使用重载。 返回类型上的重载只需要一个额外的参数:

template<class T> struct tag_t{constexpr tag_t(){}; using type=T;};
template<class T>constexpr tag_t<T> tag{};
template <typename TResult> inline TResult _from_string(const string& str){
  return _from_string( tag<TResult>, str );
}

现在我们从来没有专门_from_string,我们只是重载了 2 arg 版本。

inline unsigned long long _from_string(tag_t<unsigned long long>, const string& str) {
  return stoull(str);
}

以上甚至不是模板。

template <class T, class A>
std::vector<T,A> _from_string(tag_t<std::vector<T,A>>, const string& str) {
  // stuff that should be done only if the target type is a vector of something
}

以上是一个模板,但不是模板的专业化。

作为奖励,如果您有自定义类型 bobnamespace foo ,您只需用 namespace foo 编写_from_string( tag_t<bob>, std::string const& ) ,在大多数情况下,称为"ADL"的东西会自动找到它。

使用标记进行基于重载的调度清晰而简单,允许您自定义相关命名空间中的内容。