c++ - 编译时检查是模板类型还是 vector

标签 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 也不是我想要的。有什么建议吗?

这是我想要实现的目标的简短示例 (SSCCE):http://ideone.com/D3vBph

最佳答案

叫做标签调度:

#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();
}

关于c++ - 编译时检查是模板类型还是 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21512678/

相关文章:

c++ - 什么是单元测试模板化 C++ 方法/类/函数的好方法?

C++ 编译时字符串操作

c++ - 来自模板参数的字符串的 constexpr 长度

c++ - result_of 无法推断出返回类型

c++ - 对 `void sort::swap<int>(int*, int, int)' 的 undefined reference

C++ 命名空间和模板

c++ - X3 : How to create parser to read in sets?

python - OpenCV 找不到正确的 CUDA 版本

C++ 可变参数模板数组/访问元素

asp.net-mvc - EPPlus 失去行高