Dependencies when using C++20 conceptual template function specialization

十年热恋 提交于 2020-05-14 05:52:07

问题


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;
}

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".

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).

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)?


回答1:


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.)



来源:https://stackoverflow.com/questions/61768725/dependencies-when-using-c20-conceptual-template-function-specialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!