使用C ++ 20概念模板功能专业化时的依赖关系

时间:2020-05-13 07:29:01

标签: c++ dependencies template-specialization c++20 c++-concepts

我正在使用以下C ++ 20代码(使用当前的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代码时,出现“使用删除的函数”错误。

我本来希望C ++ 20概念专业化能够以与传统专业化相同的方式工作,但是显然存在差异,使得无法独立定义此类专业化(请参阅相关问题Module dependencies when using template function specializations

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

1 个答案:

答案 0 :(得分:2)

这些不是专长,但超载。这样,如果它们出现在呼叫者之后,它们就会被ADL查找为 only 。与往常一样,您可以对UIBezierPath (Line) going from center of one circle to edge of the other circle.使用部分专业化(在这种情况下为受约束的专业化)。 (当然,std::same_as并不是很有趣。)