我希望能够推断给定类型是否为模板类型。我查看了 boost 的类型特征类,但找不到与模板相关的 is_* 特征: http://www.boost.org/doc/libs/1_52_0/libs/type_traits/doc/html/index.html
更有趣的是,如果在编译时有办法确定模板参数的属性,例如有多少模板参数或参数是否为模板模板参数。
最佳答案
这是一个部分解决方案:
#include <iostream>
#include <type_traits>
template <typename> struct is_template : std::false_type {};
template <template <typename...> class Tmpl, typename ...Args>
struct is_template<Tmpl<Args...>> : std::true_type {};
template <typename> struct Foo {};
int main()
{
std::cout << is_template<int>::value << std::endl;
std::cout << is_template<Foo<char>>::value << std::endl;
}
问题在于模板可以具有任意结构,因此它不必只包含类型参数。您无法详尽列举所有 类型的模板参数。
但是,花一分钟时间研究这种方法,很容易生成一个参数计数器:
template <typename> struct nargs : std::integral_constant<unsigned int, 0> { };
template <template <typename...> class Tmpl, typename ...Args>
struct nargs<Tmpl<Args...> : std::integral_constant<unsigned int, sizeof...(Args)> { };
关于c++ - 有没有办法使用 C++ 类型特征来检查类型是否是模板及其任何属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13919234/