Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to differentiate between template for container and native type

Tags:

c++

templates

I have the following problem:

template<class T>
void set(std::string path, const T data)
{
   stringstream ss;
   ss << data << std::endl;
   write(path, ss.str();
}

template<class T>
void set(std::string path, const T data)
{
    std::stringstream ss;
    for(typename T::const_iterator it = data.begin(); it < data.end(); ++it)
    {
       ss << *it;
       if(it < data.end() -1 )
          ss << ", ";
    }
    ss << std::endl;
    write(path, ss.str());
}

I get the following error:

error: ‘template<class T> void myclass::set(std::string, T)’ cannot be overloaded
error: with ‘template<class T> void myclass::set(std::string, T)’

Is there a way to differentiate between container types and other types in templates?

like image 749
Steve Avatar asked Jul 19 '12 09:07

Steve


1 Answers

Use a trait:

#include <type_traits>

template <typename T>
typename std::enable_if<is_container<T>::value>::type
set (std::string const & path, T const & container)
{
    // for (auto const & x : container) // ...
}


template <typename T>
typename std::enable_if<!is_container<T>::value>::type
set (std::string const & path, T const & data)
{
    std::ostringstream oss;
    oss << data;
    write(path, oss.str());
}

You can find a suitable trait in the pretty printer code.

like image 96
Kerrek SB Avatar answered Oct 31 '22 23:10

Kerrek SB