使用C ++ 20概念模板功能专业化时的依赖关系 [英] Dependencies when using C++20 conceptual template function specialization

查看:115
本文介绍了使用C ++ 20概念模板功能专业化时的依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下C ++ 20代码(使用当前的GCC10构建)进行一些测试:

I was doing some tests with the following C++20 code (built with current GCC10):

template <typename ToT, typename FromT>
ToT myfunction(const FromT& pFrom) = delete;

template <typename ToT, typename FromT>
struct myclass
{
   inline ToT myclassmethod(const FromT& pFrom)
   {
      return myfunction<ToT, FromT>(pFrom);
   }
};

/* C++20 concepts code */
template <std::same_as<std::string> ToT, std::integral FromT>
inline ToT myfunction(const FromT& pFrom)
{
   return std::to_string(pFrom);
}

template <std::same_as<std::string> ToT, std::floating_point FromT>
inline ToT myfunction(const FromT& pFrom)
{
   return std::to_string(pFrom);
}

/* Alternative conventional code
template <>
inline std::string myfunction(const int& pFrom)
{
   return std::to_string(pFrom);
}

template <>
inline std::string myfunction(const double& pFrom)
{
   return std::to_string(pFrom);
}
*/

int main(int pArgc, char* pArgv[]) noexcept
{
   std::cout << myclass<std::string, int>().myclassmethod(10);
   std::cout << myclass<std::string, double>().myclassmethod(0.666);

   return 0;
}

使用常规代码时,所有内容都可以编译。按需使用专业。当改用C ++ 20代码时,出现使用删除的函数错误。

When using the conventional code, everything compiles fine. The specializations are used as they should. When using the C++20 code instead, I get errors "use of deleted function".

我本来希望C ++ 20概念专业化能够以与传统专业化相同的方式工作,但是显然存在差异,因此无法定义此类概念独立地进行专业化(请参见相关问题使用模板函数专业化时的模块依赖项)。

I would have expected the C++20 concepts specializations to work in the same way the conventional specializations do, but obviously there is a differences that makes it impossible to define such specializations independently (see related question Module dependencies when using template function specializations).

这是C ++ 20中所需的行为吗?在C ++ 20中,有没有一种方法可以独立地自定义概念函数模板(即,在调用之前没有声明或定义的情况下定义特殊化)?

Is this the desired behavior in C++20? Is there a way in C++20 to customize a conceptual function template independently (i.e. define the specialization without declaration or definition before calling it)?

推荐答案

不是专长,但超载。这样,如果它们出现在呼叫者之后,它们就会被ADL查找为 only 。与往常一样,您可以将部分专业化(在这种情况下为受限专业化)与转发包装器一起使用。 (当然,使用 std :: same_as 并不是很有趣。)

Those aren’t specializations, but overloads. As such, if they appear after their caller they are found only by ADL. As usual, you can use partial specializations (constrained ones in this case) with a forwarding wrapper. (Of course, that’s not very interesting with std::same_as.)

这篇关于使用C ++ 20概念模板功能专业化时的依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆