C ++检测类型是否具有模板参数
C++ detect if type has template parameter
我想统一一个接口来处理模板化和非模板化类型。有没有办法确定类型(例如 class 或函数指针)是否取决于模板参数?
例如:
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<bar>
推断出任何东西。或者,如果我定义
template<template<typename...> class>
struct temp_check : true_type {};
那么temp_check<bar>
是完全有效的,但我不知道如何类比检查foo
。如果它是有效的 C++
,则需要的是这样的东西
template<template<> class A> struct temp_check<A> : false_type {};
是否有某种机制可以检查两者?
我会使用超载集的力量:
#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
}
让给用户:使用模板函数提供特征;)
我想统一一个接口来处理模板化和非模板化类型。有没有办法确定类型(例如 class 或函数指针)是否取决于模板参数?
例如:
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<bar>
推断出任何东西。或者,如果我定义
template<template<typename...> class>
struct temp_check : true_type {};
那么temp_check<bar>
是完全有效的,但我不知道如何类比检查foo
。如果它是有效的 C++
template<template<> class A> struct temp_check<A> : false_type {};
是否有某种机制可以检查两者?
我会使用超载集的力量:
#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
}
让给用户:使用模板函数提供特征;)