小编Cam*_*owe的帖子

如何判断模板类型是否是模板类的实例?

我有一个采用模板类型来确定返回值的函数。有什么方法可以在编译时判断模板类型是否是模板类的实例化?

例如

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>>();
Run Code Online (Sandbox Code Playgroud)

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

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 …
Run Code Online (Sandbox Code Playgroud)

c++ templates type-traits

1
推荐指数
3
解决办法
1183
查看次数

标签 统计

c++ ×1

templates ×1

type-traits ×1