Given the code in C ++ 17:

template<class T> struct Ok { T value; }; template<> struct Ok<void> {}; // template deduction guides template<class T> Ok(T) -> Ok<T>; 

Template deduction guides allow having the type Ok<T> call Ok as a function (this is what the constructor actually looks like):

 auto c = Ok(5); // T deduced as int // без template deduction guide я так писать не могу, // но должен писать: auto c = Ok<int>(5); // T can not be deduced :( 

The question is how to rewrite it in C ++ 14 or lower? So I just wrote:

 auto c = Ok("hello"s); // T deduced as std::string 

But with an arbitrary type.

    2 answers 2

     template<class T> Ok<std::decay_t<T>> makeOk(T&& arg){ return Ok<std::decay_t<T>>{std::forward<T>(arg)}; } auto c = makeOk(5); auto d = makeOk(std::make_unique<double>(6.7)); 

      I started writing as a comment, but did not meet the limits.


      The answer has already been given, but by and large it was in your question when you compared the constructor with the function.

      The classic solution is the use of template make- functions. Any make_pair , make_unique , make_shared bright examples of this.

      Additionally, I want to note that if the type Ok clearly indicated only during creation (via the constructor function), then you can enter a bit from the other end than Viktor Smirnov did in his answer, and use Ok instead of makeOk as the name of the generating function. And the structure itself is renamed, say, Ok_ . Maybe in this way it will be possible to reduce the number of places that require code changes.