C++ 检测类型是否有模板参数 [英] C++ detect if type has template parameter
问题描述
我想统一一个接口来处理模板化和非模板化类型.有没有办法确定类型(例如类或函数指针)是否依赖于模板参数?
I would like to unify an interface to work with both templated and non-templated types. Is there a way to determine whether a type, such as a class or a function pointer is depends on a template parameter?
例如:
struct foo {};
template<typename T> struct bar {};
// This works if the template parameter is provided
template<typename> struct is_templated : false_type {};
template<template<typename...> class Obj, typename...Args>
struct is_templated<Obj<Args...>> : true_type {};
template<typename T> constexpr auto is_templated_v = is_templated<T>::value;
在这种情况下,is_template_v<foo>
是假的,而 is_template_v<bar<int>>
是真的,但我不能用 is_template_v
.或者,如果我定义
In this case, is_template_v<foo>
is false and is_template_v<bar<int>>
is true, but I can't just deduce anything with is_template_v<bar>
. Alternatively, if I define
template<template<typename...> class>
struct temp_check : true_type {};
然后 temp_check
是完全有效的,但我不知道如何类似地检查 foo
.如果它是有效的 C++,则需要这样的东西
Then temp_check<bar>
is perfectly valid, but I don't know how I would analogously check foo
. What is needed is something like this if it were valid C++
template<template<> class A> struct temp_check<A> : false_type {};
是否有某种机制可以同时检查两者?
Is there some mechanism that could check both?
推荐答案
我会使用重载集的力量:
I'd use the power of overload sets:
#include <iostream>
#include <type_traits>
struct foo {};
template<typename T> struct bar {};
template<template<class ...> class T, class... TArgs>
constexpr bool is_template() { return true; }
template<class T>
constexpr bool is_template() { return false; }
int main()
{
std::cout << is_template<foo>() << '\n'; // 0
std::cout << is_template<bar>() << '\n'; // 1
}
让给用户:使用模板函数提供一个特征;)
Let to the user: use the template function to provide a trait ;)
这篇关于C++ 检测类型是否有模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!