在编译时检查是模板类型向量

时间:2014-02-02 15:59:41

标签: c++ templates

我可以想象以下代码:

template <typename T> class X
{
  public:
   T container;

   void foo()
   {
      if(is_vector(T))
         container.push_back(Z);
      else
         container.insert(Z);
   }
}

// somewhere else...

X<std::vector<sth>> abc;
abc.foo();

如何编写,成功编译?我知道类型特征,但是当我定义时:

template<typename T> struct is_vector : public std::false_type {};

template<typename T, typename A>
struct is_vector<std::vector<T, A>> : public std::true_type {};

它无法编译:

error: no matching function for call to 'std::vector<sth>::insert(Z)'

static_assert也不是我想要的。有什么建议吗?

以下是我想要实现的一个简短示例(SSC C E):http://ideone.com/D3vBph

5 个答案:

答案 0 :(得分:28)

命名为tag dispatching:

#include <vector>
#include <set>
#include <type_traits>

template<typename T> struct is_vector : public std::false_type {};

template<typename T, typename A>
struct is_vector<std::vector<T, A>> : public std::true_type {};

template <typename T>
class X {
    T container;

    void foo( std::true_type ) {
        container.push_back(0);
    }
    void foo( std::false_type ) {
        container.insert(0);
    }
public:
    void foo() {
        foo( is_vector<T>{} );
    }
};

// somewhere else...
int main() {
    X<std::vector<int>> abc;
    abc.foo();

    X<std::set<int>> def;
    def.foo();
}

答案 1 :(得分:6)

另一个值得考虑的方法是使用SFINAE检测push_back函数的存在。这稍微更通用,因为它将转换为实现push_back的其他容器。

template<typename T>
struct has_push_back
{
    template<typename U>
    static std::true_type test(
        decltype((void(U::*)(const typename U::value_type&)) &U::push_back)*);

    template<typename>
    static std::false_type test(...);

    typedef decltype(test<T>(0)) type;
    static constexpr bool value = 
        std::is_same<type, std::true_type>::value;
};

请注意,它目前仅检测push_back(const T&)而非push_back(T&&)。检测两者有点复杂。

以下是如何使用它来实际插入。

template<typename C, typename T>
void push_back_impl(C& cont, const T& value, std::true_type) {
    cont.push_back(value);
}

template<typename C, typename T>
void push_back_impl(C& cont, const T& value, std::false_type) {
    cont.insert(value);
}

template<typename C, typename T>
void push_back(C& cont, const T& value) { 
    push_back_impl(cont, value, has_push_back<C>::type());
}

std::vector<int> v;
push_back(v, 1);

std::set<int> s;
push_back(s, 1);

老实说,这个解决方案比我原先预期的要复杂得多,所以除非你真的需要,否则我不会使用它。虽然支持const T&T&&并不是很难,但是你需要维护更加神秘的代码,这在大多数情况下可能都不值得。

答案 2 :(得分:4)

仅使用插入:

#include <iostream>
#include <vector>
#include <set>

template <typename T>
class X
{
    public:
    T container;

    template <typename U>
    void insert(const U& u) {
        container.insert(container.end(), u);
    }
};

int main() {
    X<std::vector<int>> v;
    v.insert(2);
    v.insert(1);
    v.insert(0);

    for(std::vector<int>::const_iterator pos = v.container.begin();
        pos != v.container.end();
        ++pos)
    {
        std::cout << *pos;
    }
    std::cout << '\n';

    X<std::set<int>> s;
    s.insert(2);
    s.insert(1);
    s.insert(0);

    for(std::set<int>::const_iterator pos = s.container.begin();
        pos != s.container.end();
        ++pos)
    {
        std::cout << *pos;
    }
    std::cout << '\n';
}

答案 3 :(得分:1)

这是使用void_t的典型方法:

template <typename T>
using void_t = void;  // C++17 std::void_t

template <typename C, typename = void>  // I'm using C for "container" instead of T, but whatever.
struct has_push_back_impl : std::false_type {};

template <typename C>
struct has_push_back_impl<C, void_t<decltype(std::declval<C>().push_back(typename C::value_type{}))>>
    : std::true_type {};  // Note that void_t is technically not needed in this case, since the 'push_back' member function actually returns void anyway, but it the general method to pass the type into void_t's template argument to obtain void.  For example, the 'insert' function from std::set and std::map do NOT return void, so 'has_insert' will need to use void_t.

template <typename C>
using has_push_back = has_push_back_impl<C>;  // void passed to the second template argument by default, thus allowing the second specialization to be used instead of the primary template whenever C has a push_back member function.

此方法适用于has_insert关联容器,即使std::setstd::map&#39; s insert函数返回std::pair<typename T::iterator, bool>std::multimap::insert 1}}返回std::multimap::iterator(这是Ze Blob方法不起作用的一种情况)。

答案 4 :(得分:1)

如果使用constexpr if,则表示操作正确。此C ++ 17代码编译:

#include <iostream>
#include <type_traits>
#include <vector>
#include <list>

template<typename T> struct is_vector : public std::false_type {};

template<typename T, typename A>
struct is_vector<std::vector<T, A>> : public std::true_type {};


template <typename T>
class X
{
  public:
   T container;

   void foo()
   {
      if constexpr(is_vector<T>::value){
        std::cout << "I am manipulating a vector" << std::endl;
        // Can access container.push_back here without compilation error
      }
      else {
         std::cout << "I am manipulating something else" << std::endl;
      }
   }
};

int main() {
    X<std::vector<int>> abc;
    abc.foo(); // outputs "I am manipulating a vector"

    X<std::list<int>> def;
    def.foo(); // outputs "I am manipulating something else"
}