我有一个函数,它采用模板类型来确定返回值。有没有办法在编译时判断模板类型是否是模板类的某个实例?
前任。
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>>();
我知道可以通过这样做来解决这个问题
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
实例,我不想测试所有可能的类型。
这是一个选项:
#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
为模板实例化类型的结构。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句