0

I'm not new to programming but i try to understand the concept of concepts in c++20 a little bit more in depth.

situation: I'm playing around with a method in a class like (content of my header file):

// in my mind: a concept testing if there is a typename matching with 
// std::to_string(...)
template<typename T>
concept IsStringable = requires (T t) {
  { std::to_string(t) };  // NOTE: there must be a to_string overloaded version
                          // with type T
};

class example_class_with_concept_methode {
 private:
  // some unnecessary stuff

  // implementation outsourced to cpp file
  std::string _replacePlaceholder(std::string fmtMsg,
                                  std::string reg,
                                  std::string replacementMsg);

 public:
  // ctor & co.

  std::string processMessage(std::string msg, IsStringable auto replaceMsgValue) {
    std::string replaceMsg = std::to_string(replaceMsgValue);
    return _replacePlaceholder(fmtMsg, _pattern, replaceMsg);

}; // class example_class_with_concept_methode

The CMakeLists.txt files are working with the above shown code (GCC 10.2.1 x86_64-linux-gnu, CMake 3.18.4). But target solution would be outsourcing the concept method also to the cpp file (what was done with all other class methods).

BUT (question): If I outsource this one method to cpp I'm getting multiple errors for undefined references for different versions the compiler would make out of the concept statement for replaceMsgValue. What am I doing wrong here?

Do I need to keep this implementation in header file or is there a way to outsource it to the cpp file?

  • 1
    A function with a placeholder type (i.e. `auto`) in a parameter is not actually a function, but an _abbreviated function template_. Function templates must usually be implemented in header files with the common exception of using the explicit template instantiation method. It is no different than for usual templates (which I hope you learned about before learning concepts, which are an advanced feature that only makes sense in the context of templates). – user17732522 Nov 25 '22 at 10:57
  • Oh, I just noticed that I misread "_I'm not new to programming_" as "_I'm new to programming_" which can be seen here much more often. In that case you can probably disregard the last part of my previous comment. – user17732522 Nov 25 '22 at 11:02
  • Anyway the information to use auto/template is not so common for me atm. Normally i'm using c# where templates can be used nearly everywhere. But from my past i know separation in c++ should be consequent in header and source code file. So it was irritating not to be able to use it that way. From the other hint (duplicate) I also understand that a possible workaround would be to explicitly instantiate all candidates i need in source code file. Thanks to all, – mirrowwinger Nov 25 '22 at 11:58

0 Answers0