相关疑难解决方法(0)

匹配别名模板作为模板参数

请考虑以下代码:

#include <type_traits>

template<template<class...> class T, class... U>
struct is_specialization_of : std::false_type{};

template<template<class...> class T, class... U>
struct is_specialization_of<T, T<U...>> : std::true_type{};

template<class T, class U = int>
struct test{};

// (1) ok
static_assert(is_specialization_of<test, test<int>>::value, "1");

template<class T>
using alias = test<T>;

// (2) fails
static_assert(is_specialization_of<alias, alias<int>>::value, "2");

int main()
{
}
Run Code Online (Sandbox Code Playgroud)

为什么(2),即static_assert使用别名模板,失败?

(2)中的模板参数推导过程与(1)中的模板参数推导过程有何不同?

c++ templates language-lawyer c++11

14
推荐指数
1
解决办法
573
查看次数

在模板中使用模板别名而不是模板

从上一个问题:

执行static_assert模板类型是另一个模板

Andy Prowl为我提供了这个代码,允许我static_assert模板类型是另一种模板类型:

template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of : public std::false_type { };

template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of<TT, TT<Ts...>> : public std::true_type { };

template<typename T>
struct foo {};

template<typename FooType>
struct bar {
  static_assert(is_instantiation_of<foo,FooType>::value, ""); //success
};

int main(int,char**)
{
  bar<foo<int>> b; //success
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这非常有效.

但是如果我改变这样的代码来使用别名foo,事情会变得糟糕:

template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of : public std::false_type { };

template<template<typename...> class TT, typename... Ts>
struct is_instantiation_of<TT, TT<Ts...>> : public …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11

11
推荐指数
1
解决办法
2859
查看次数

标签 统计

c++ ×2

c++11 ×2

templates ×2

language-lawyer ×1