xin*_*aiz 11 c++ templates sfinae type-traits c++14
我们可以检测员function template,variable template, class/ struct/ union template或alias template不知道量或性质template/ non-template参数?
当我试着考虑这个时,没有什么真正想到的.但是让我们有成员函数模板的结构:
struct foo
{
// Really random. Let's assume we don't know this declaration, just the name "bar"
template <class T, std::size_t N, class... Args>
void bar(T a, T b, T(&c)[N], Args const& ...);
};
Run Code Online (Sandbox Code Playgroud)
如何检查foo::bar模板是否存在?
基于实例化的类型特征在这里不适用,因为(理论上)我们不知道应该使用哪些参数,按什么顺序以及有多少参数.也许一些神奇的查找方法是合适的?或者也许这是不可能的?
在搜索时,我发现了这个问题,但答案中的解决方案需要有关性质的知识template.
这是我第一次尝试检测失败struct template:
struct foo
{
template<class T>
struct bar { };
};
template <class T, class = void>
struct has_template_bar : std::false_type
{ };
template <class T>
struct has_template_bar <T, void> : std::true_type
{
template<template<class...> class tplt_tplt = T::bar> // Invalid default argument
struct placebo
{ };
};
Run Code Online (Sandbox Code Playgroud)
我可以向您展示如何检测结构模板:
template < class > struct check_template : std::false_type {};
// Specialize for template classes
template <template<class...> class X, class... Args>
struct check_template< X<Args...> > : std::true_type {};
Run Code Online (Sandbox Code Playgroud)
然后,您也许可以玩弄declval,void_t等检测成员模板.
如果要检测类型与元类型,如即模板std::vector,而不是std::vector<int>,你可以做到以下几点:
#include <iostream>
template <template<class...> class>
constexpr bool is_template()
{
return true;
}
template <class>
constexpr bool is_template()
{
return false;
}
struct Foo{};
template<class>
struct TemplateFoo{};
int main()
{
std::cout << std::boolalpha;
std::cout << is_template<Foo>() << std::endl;
std::cout << is_template<TemplateFoo>() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果元类型具有任何非类型参数,则解决方案将不起作用
template<class, int> struct X{};
Run Code Online (Sandbox Code Playgroud)