如何判断模板类型是否是模板类的实例? [英] How to tell if template type is an instance of a template class?

查看:53
本文介绍了如何判断模板类型是否是模板类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个采用模板类型来确定返回值的函数.有没有办法在编译时判断模板类型是否是模板类的实例化?

I have a function that takes a template type to determine a return value. Is there any way to tell at compile time if the template type is some instantiation of a template class?

例如.

class First { /* ... */ };

template <typename T>
class Second { /* ... */ };

using MyType = boost::variant<First, Second<int>, Second<float>>;

template <typename SecondType>
auto func() -> MyType {
    static_assert(/* what goes here?? */, "func() expects Second type");
    SecondType obj;
    // ...
    return obj;
}

MyType obj = func<Second<int>>();

我知道这样做可以解决这个问题

I know it is possible to get around this by doing

template <typename T>
auto func() -> MyType {
    static_assert(std::is_same<T, int>::value || std::is_same<T, float>::value,
                  "func template must be type int or float");

    Second<T> obj;
    // ...
    return obj;
}

MyType obj = func<int>();

一般来说,我只是好奇是否有一种方法可以测试类型是否是模板类的实例化?因为如果 MyType 最终有6个 Second 实例化,我就不必测试所有可能的类型.

I'm just curious in general if there is a way to test if a type is an instantiation of a template class? Because if MyType ends up having 6 Second instantiations, I don't want to have to test for all possible types.

推荐答案

以下是一个选项:

#include <iostream>
#include <type_traits>
#include <string>

template <class, template <class> class>
struct is_instance : public std::false_type {};

template <class T, template <class> class U>
struct is_instance<U<T>, U> : public std::true_type {};

template <class>
class Second 
{};

int main()
{
    using A = Second<int>;
    using B = Second<std::string>;
    using C = float;
    std::cout << is_instance<A, Second>{} << '\n'; // prints 1
    std::cout << is_instance<B, Second>{} << '\n'; // prints 1
    std::cout << is_instance<C, Second>{} << '\n'; // prints 0
}

基本上,它将 is_instance 结构专用于作为模板实例化的类型.

It's basically specializing the is_instance struct for types that are instantiations of a template.

这篇关于如何判断模板类型是否是模板类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆