基于如何判断模板类型是否是模板类的实例?并检查类是否是模板专业化?我创建了以下变体来检查MyClass1, MyClass2or 的特定实例MyClass3:
template <class T, template <class...> class Template>
constexpr bool is_instance_of_v = false;
template <template <class...> class Template, class... Args>
constexpr bool is_instance_of_v<Template<Args...>, Template> = true;
template<class T> struct MyClass1 { };
template<class T, class B> struct MyClass2 { };
template<class T, bool B> struct MyClass3 { };
int main(int argc, char* argv[])
{
constexpr bool b1 = is_instance_of_v<MyClass1<float>, MyClass1>;
constexpr bool b2 = is_instance_of_v<MyClass1<float>, MyClass2>;
// constexpr bool …Run Code Online (Sandbox Code Playgroud) 我希望能够推断给定类型是否是模板类型。我查看了 boost 的类型特征类,但找不到与模板相关的 is_* 特征: http://www.boost.org/doc/libs/1_52_0/libs/type_traits/doc/html/index.html
更有趣的是,如果有方法在编译时确定模板参数的属性,例如有多少模板参数或参数是否是模板模板参数。
在下面的代码中:
template <typename T>
struct templatedStruct
{
};
template <typename T>
void func(T arg)
{
// How to find out if T is type templatedStruct of any type, ie., templatedStruct<int> or
// templatedStruct<char> etc?
}
int main()
{
templatedStruct<int> obj;
func(obj);
}
Run Code Online (Sandbox Code Playgroud)
是从其他东西继承 templatedStruct 的唯一方法吗?
struct Base {};
template <typename T>
struct templatedStruct : Base
{
};
template <typename T>
void func(T arg)
{
std::is_base_of_v< Base, T>;
std::derived_from<T, Base>; // From C++ 20
}
Run Code Online (Sandbox Code Playgroud)