是否可以仅通过标识符检查成员模板的存在? [英] Is it possible to check for existence of member templates just by an identifier?
问题描述
我们可以检测成员函数模板
,变量模板
,类
/ struct
/ 联合模板
或别名模板
未知数量或模板
/ 非模板
参数的性质?
Can we detect member function template
, variable template
, class
/struct
/union template
or alias template
without knowing amount, or nature of template
/non-template
parameters?
当我想到这一点,没有什么真正的想法。但是让我们有成员函数模板的结构:
When I try to think about this, nothing really comes to my mind. But let's have structure with member function 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& ...);
};
如何检查 foo :: bar
template exists?
How do I check if the foo::bar
template exists?
基于实例化的类型特征在这里不适用,因为(理论上)我们不知道 ,以什么顺序和有多少。也许一些魔术查找方法会合适吗?
Instantiation-based type traits don't apply here, because (theoretically) we don't have knowledge of which parameters we should use, in what order and how many of them. Maybe some magic lookup method would be appropriate? Or maybe it's just impossible?
搜索时,我发现这个问题,但答案中的解决方案需要有关
When searching, I found this question, but solutions in the answers require knowledge about nature of 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
{ };
};
推荐答案
我可以告诉你如何检测结构模板:
I can show you how to detect a struct template:
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 {};
然后你可以使用 declval
, void_t
等检测成员模板。
You can then probably play around with declval
, void_t
, etc. to detect member templates.
如果您想检测类型与元类型,例如 std :: vector
而不是 std :: vector< int>
的模板,可以执行以下操作:
In case you want to detect types vs. meta-types, i.e. templates like std::vector
and not std::vector<int>
, you can do the following:
#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;
}
请注意, meta-type有任何非类型参数,如
Note that the solutions won't work if the meta-type has any non-type parameters, like
template<class, int> struct X{};
这篇关于是否可以仅通过标识符检查成员模板的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!