c++ - 我如何知道 C++ 模板是容器还是类型?

标签 c++ templates stl

<分区>

我给出以下代码来显示我的问题:

template<T>
void my_fun(T &obj)
{
  if(obj is a type like float, std::string, double)
   {
       perform1()
  }
  if(obj is a container like std::vector, std::list)
  {
      perform2()
 } 
}
std::vector<int> abc;
my_fun(abc);
int d;
my_fun(d);

那么我的问题是,我怎么知道模板指的是简单类型还是容器?谢谢。

最佳答案

你可以通过 expression SFINAE 编写你自己的特征和 enable_if有多个重载。这是一个使用 void_t 的解决方案trick (大概会出现在 C++17 中):

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

template<typename ...>
using to_void = void; // maps everything to void, used in non-evaluated contexts

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

template<typename T>
struct is_container<T,
        to_void<decltype(std::declval<T>().begin()),
                decltype(std::declval<T>().end()),
                typename T::value_type
        >> : std::true_type // will  be enabled for iterable objects
{};

template<typename T>
void f(T param, typename std::enable_if<is_container<T>::value>::type* = nullptr)
{
    std::cout << "Container\n";
}

template<typename T>
void f(T param, typename std::enable_if<std::is_fundamental<T>::value>::type* = nullptr)
{
    std::cout << "Fundamental\n";
}

template<typename T>
void f(T param, 
    typename std::enable_if<!std::is_fundamental<T>::value>::type* = nullptr, 
    typename std::enable_if<!is_container<T>::value>::type* = nullptr)
{
    std::cout << "Other\n";
}

struct Foo{};

int main()
{
    int x{};            // fundamental
    std::vector<int> v; // container
    Foo s{};    // other

    f(x);
    f(v);
    f(s);
}

Live on Coliru

关于c++ - 我如何知道 C++ 模板是容器还是类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38077228/

相关文章:

c++ - double(?) 模板成员运算符的定义

c++ - STL 列表和迭代器

c++ - 如何访问成对元素的映射?

C++ 迭代器 : Can iterators to an abstract class be implemented as a nested class?

c++ - 无法在 Xcode 3 中打开文件

c++ - 模板特化站点报告 "too few template-parameter-lists"错误

c++ - 模板元编程 : (trait for? ) 将指定模板分解为类型 T<T2,T3 N,T4, ...>

c++ - 删除元素后,(c++) vector 会缩小吗?

c++ - 将字形索引转换为 Unicode 字符

c++ - 解引用迭代器值类型的迭代器