gpt4 book ai didi

c++ - 我可以重复使用同一个模板来声明/定义多个东西(不复制模板代码)吗?

转载 作者:太空狗 更新时间:2023-10-29 21:37:33 30 4
gpt4 key购买 nike

我目前正在编写一个类,其中有一些精美的模板来定义它的一些成员,但其中一些模板是完全相同的。考虑以下代码(这些都是类成员):

template <typename T, typename = enable_if_t<is_convertible<int, T>::value>>
T get() const { return convert_self_to_int(); }

template <typename T, typename = enable_if_t<is_constructible<T, string>::value>, typename = void>
T get() const { return convert_self_to_string(); }

template <typename T, typename = enable_if_t<is_convertible<int, T>::value>>
operator T() const { return get<T>(); }

template <typename T, typename = enable_if_t<is_constructible<T, string>::value>, typename = void>
operator T() const { return get<T>(); }

如您所见,我有一个名为 get 的模板化成员函数,它使用很长且有点难以阅读的模板代码。

This part is not essential for the question, but here's a brief explanation of all those fancy templates: get is a function which can return data in one of two formats: if the template argument T is a type into which an int can be converted, then the integral representation of the data is returned (thus triggering the conversion to the requested type, which we know is possible). If T is something that can be constructed from a string, then the string representation of the data is returned (again, triggering the construction of T from a string). Any other type that does not fall into these categories will simply cause a compile-time error, which is exactly what this code is intended to do.

这个类还定义了简单的转换运算符,用get来写。

既然这些运算符使用完全相同的模板 作为get 的相应定义,我能否以某种方式避免重复所有那些讨厌的模板代码?我可以重复使用一行模板代码来定义多个东西,使代码更具可读性吗?

最佳答案

你可以只拥有 operator T()转发到get<T>使用 SFINAE。这样,您只需要一个 operator T() :

template <class T, class = decltype(std::declval<ClassName>().get<T>())>
operator T() const {
return get<T>();
}

此外,对于多个 SFINAE,而不是不断添加额外的 typename=void您可以更改您的 enable_if_t给你一个默认的int :

template <class T, std::enable_if_t<std::is_convertible<int, T>::value, int> = 0>
T get() const { return convert_self_to_int(); }

template <class T, std::enable_if_t<std::is_convertible<std::string, T>::value, int> = 0>
T get() const { return convert_self_to_string(); }

现在,不幸的是,这在 clang 中不起作用,所以我只是建议翻转顺序。有 operator T()是 SFINAE-d:

template <class T, std::enable_if_t<std::is_convertible<int, T>::value, int> = 0>
operator T() const { return convert_self_to_int(); }

template <class T, std::enable_if_t<std::is_convertible<std::string, T>::value, int> = 0>
operator T() const { return convert_self_to_string(); }

还有get向前:

template <class T> T get() const { return operator T(); }

这里的优点是我们不会复制任何东西,而且 std::is_convertible<>类型特征将正常工作 - 自 operator T()是 SFINAE-d。关于 get<T>() 的测试会失败,但这似乎不是通常可测试的东西。

关于c++ - 我可以重复使用同一个模板来声明/定义多个东西(不复制模板代码)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37353220/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com