Check if type can be an argument for boost :: lexical_cast <string>

I have the following attribute class ( IsLexCastable) to check if a type can be converted to a string by calling boost::lexical_cast<string>. It erroneously returns truefor vector<int>.

#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

namespace std
{
/// Adding to std since these are going to be part of it in C++14.
template <bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
}

template <typename T, typename = void>
struct IsLexCastable : std::false_type
{
};

template <typename T>
struct IsLexCastable<T, std::enable_if_t<std::is_same<std::string, decltype(boost::lexical_cast<std::string>(std::declval<T>()))>::value> > : std::true_type
{
};

int main()
{
  vector<int> a = {1, 2, 3};
  //  cout << lexical_cast<string>(a) << endl;
  cout << IsLexCastable<decltype(a)>::value << endl;
  return 0;
}

This program prints 1, but lexical_cast<string>(a)leads to a compilation error. What is the correct way to implement it IsLexCastable?

(This was compiled with g++48 -std=c++11and boost 1.55.0.)

+4
source share
2 answers

, lexical_cast static_assert. , std::ostream:

template <typename T, typename=void>
struct IsLexCastable : std::false_type {};

// Can be extended to consider std::wostream as well for completeness
template <typename T>
struct IsLexCastable<T,
            decltype(void(std::declval<std::ostream&>() << std::declval<T>()))>
  : std::true_type {};

.
OutputStreamable , - .


?

decltype . lexical_cast, , , SFINAE.

[temp.inst]/10:

- , , (14.8.3).

+4

, . , lexical_cast T. Boost has_right_shift has_left_shift, .

template <typename T, typename=void>
struct IsLexCastable : std::false_type {};

template <typename T>
struct IsLexCastable<T,
        typename std::enable_if<boost::has_right_shift<T>::value>::type>
  : std::true_type {};
0

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


All Articles