2

Can I turn a class into a template class without breaking user code? I am trying to change a class to accept template parameters, but at the same time, I would like to avoid breaking existing client code. In more detail, the existing codebase was

class A{ // some code };

I turned this into the following:

template <type T = defaultType>
class A{ // some code };

The non-templatized code was effectively written for defaultType. Can I do anything so that existing code does not break when the code is compiled without c++17 (or greater) support? For example, the following should be valid:

A a{}; //existing code; works under c++17 with CTAD. How to use in c++14?
A<typeFoo> b{} //new code, if users decide to use a different template argument;

I am grateful for any hints or suggestions!

fabian
  • 1,413
  • 1
  • 13
  • 24
  • How is your question related to CTAD? I can't see any argument which will be deduced ( construcors are not taking arguments in your example... – Klaus Jun 05 '21 at 15:21
  • @Klaus: I was wondering the same, and it is not mentioned, for example, in Nicolai Josuttis' book. However, see the second answer [here](https://stackoverflow.com/questions/15373823/template-default-arguments/50970942#50970942). I also tried it with my gcc 10 and it works. – fabian Jun 05 '21 at 15:25
  • CTAD won’t save you if you have parameters or members of, or pointers or references to, that type anywhere. So C++17 surely doesn’t matter here. – Davis Herring Jun 05 '21 at 15:34

1 Answers1

6

You can do what std::string does:

template <typename T>
class basic_A{ ... };

using A = basic_A<defaultType>;
Caleth
  • 52,200
  • 2
  • 44
  • 75