相关疑难解决方法(0)

统一类型和非类型模板参数

我有一个类型特征,检查给定类型是否是给定类模板的实例:

template <template <typename...> class C, typename T>
struct check_is_instance_of : std::false_type { };

template <template <typename...> class C, typename ...Ts>
struct check_is_instance_of<C, C<Ts...>> : std::true_type { };

template <template <typename...> class C, typename T>
struct is_instance_of : check_is_instance_of<C, std::remove_cv_t<T>> { };
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不适用于非类型模板参数,因为它们不会被可变参数模板参数"捕获",因此

is_instance_of<std::integral_constant, std::true_type>
Run Code Online (Sandbox Code Playgroud)

产生编译错误.有没有办法编写一个is_instance_of适用于任意数量的类型和非类型模板参数的实现?

c++ template-meta-programming

9
推荐指数
1
解决办法
332
查看次数

检查类是否是模板专业化?

如何检查给定类型是否是特定类模板的特化?例如,给定

template <class T>
struct A {};
Run Code Online (Sandbox Code Playgroud)

我怎么可以检查是否CompareTA<*>某种类型*如下所示:

template<class CompareT>
void compare(){
   // is this A ?
   cout << is_same< A<*> , CompareT >::value;     // A<*> ????
}

int main(){
  compare< A<int> >();
}
Run Code Online (Sandbox Code Playgroud)

例如,这里 A<int>应匹配A<*>并打印1.

c++ templates

6
推荐指数
2
解决办法
2042
查看次数

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

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

例如

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
查看次数