yipo
5/5/2016 - 1:33 PM

A trick to use the filesystem library as if there is a standard one of C++17.

A trick to use the filesystem library as if there is a standard one of C++17.

#pragma once

// Use the filesystem library as if there is a standard one of C++17.

// Filesystem library
// http://en.cppreference.com/w/cpp/filesystem

#if _MSC_VER >= 1700 // VS2012

// Use the one from 'std::tr2' to avoid depending on Boost DLLs.

// <filesystem>
// http://msdn.microsoft.com/library/hh874694

#include <filesystem>
#include <string>

// Note that 'std::tr2::sys::path' always translates the path into the general format (POSIX, forward-slash).
// To get a native format (Windows, backslash) path we preferred, define our own 'path' class
// based on the existing 'std::tr2::sys::basic_path' template, and provide proper slash/altslash traits.

// Class path: Generic format vs. Native format
// http://www.boost.org/doc/libs/1_57_0/libs/filesystem/doc/tutorial.html#class-path-formats

// On Windows platform, 'boost::filesystem::path' gives paths with backslash natively.

namespace std
{
    namespace filesystem
    {
        struct path_traits : public tr2::sys::path_traits
        {};

        typedef tr2::sys::basic_path<string, path_traits> path;

        using namespace tr2::sys;
    }

    namespace tr2
    {
        namespace sys
        {
            template <> struct colon<filesystem::path>
            {
                static const char value = ':';
            };
            template <> struct dot<filesystem::path>
            {
                static const char value = '.';
            };
            template <> struct slash<filesystem::path>
            {
                static const char value = '\\';
            };
            template <> struct _Altslash<filesystem::path>
            {
                static const char value = '/';
            };
        }
    }
}

inline std::filesystem::path operator /(const std::filesystem::path &a, const std::string &b)
{
    return a / std::filesystem::path(b);
}

#else

// For Visual Studio older than 2012, Boost libraries are required.

// Filesystem Library Reference Documentation
// http://www.boost.org/doc/libs/1_57_0/libs/filesystem/doc/reference.html

#include <boost/filesystem.hpp>

namespace std
{
    namespace filesystem
    {
        using namespace boost::filesystem;
    }
}

#endif