4

次のように、さまざまなタイプの多くのメンバーをオーバーロードするクラスがあります。

template<typename T, typename Allocator>
Stream& operator << (Stream &Destination, const std::list<T, Allocator> &Value)

template<typename T, typename Allocator>
Stream& operator << (Stream &Destination, const std::vector<T, Allocator> &Value)

そして今、私はそれを文字列に特化しようとしています..次を使用して文字列を作成しました:

template<typename T>
struct is_string : public std::integral_constant<bool, std::is_same<char*, typename std::decay<T>::type>::value || std::is_same<const char*, typename std::decay<T>::type>::value> {};

template<>
struct is_string<std::string> : std::true_type {};

そして、次のように特化したいと思います。

template<typename T = typename is_string<T>::value_type> //How?
Stream& operator << (Stream &Destination, const typename is_string<T>::value_type &Value)
{
    std::cout<<"HERE";
    return Destination;
}

//I can do:
template<typename T = std::string> //works fine.
Stream& operator << (Stream &Destination, const typename is_literal<T>::value_type &Value)
{
    std::cout<<"HERE";
    return Destination;
}

T が渡された文字列型になるように、すべての文字列型で機能するように文字列を修正するにはどうすればよいですか?

編集: char*、const char*、char[]、const char[]、std::string など、すべての文字列型に特化するようにこれを実行しようとしています。

4

1 に答える 1

4

私は次のようなものを使用します:

#include <type_traits>
#include <ostream>

template <typename T>
typename std::enable_if<is_string<T>::value, std::ostream &>::type
operator<<(std::ostream & o, T const & x)
{
    return o << x;  // or whatever
}

Tこれにより、特性を満たす場合にのみオーバーロードが有効になります。

(柔軟性を高めるために、すべての ostream テンプレート パラメーターを変数にすることもできます。)

于 2013-08-18T23:48:52.540 に答える