我给出以下代码来显示我的问题:
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