Return optional from a common function in C ++

What other way to return a common optional parameter in C ++ without using optional<T>{} from BOOST library

Example

 template<class T>
    T search(T arg) {
        // this function is just to show the idea of what I am trying to ac
       if (found) return arg;
       return ?<---
    }

I mean, if I know the most common type that will call this function, I could

returns T (-1); for int

return T ("not found"); for string

return nullprt; for pointer type

But this strikes the patrimonial goal. Should there be another way? Thanks for helping

+4
source share
1 answer

, boost::optional std::optional . , ? std::optional, .

.

template <class T>
bool search( T arg, T & out );

, . , T . , T , .

, .

template <class T>
const T & search( T arg );

template <class T>
const T * search( T arg );

, std::optional , boost::optional, std::optional .

.

. , . boost::optional std::optional ( , ), , .

, .

, , . , , , , . , :

template <class T>
struct DummyValue;

template <>
struct DummyValue<int>
{
    static constexpr const int value = -1;
    // Or:
    // static int makeDummyValue();
};
// And so on ...
+9

Source: https://habr.com/ru/post/1668695/


All Articles