传递一个类模板作为模板参数

时间:2018-12-15 19:57:00

标签: c++ c++17 template-meta-programming

是否可以将类模板(如std::vector而不是像std::vector<int>实例化)作为模板参数?我想编写一个检查给定类型是否为给定模板实例的类型。我知道编译器不允许按原样传递未实例化的模板,但是我想知道是否有比我更好的解决方法。

我的实现(请注意,我在最底部擦除了TArgs

#include <type_traits>

template <typename Instance, typename Template>
struct IsInstanceOf : std::false_type {};

template <
      template <typename...> typename Instance,
      template <typename...> typename Template, 
      typename... IArgs,
      typename... TArgs>
struct IsInstanceOf<Instance<IArgs...>, Template<TArgs...>>
    : std::is_same<Instance<IArgs...>, Template<IArgs...>> {};

此实现有效,但我必须使用某种类型实例化模板,例如:

IsInstanceOf<std::vector<float>, std::vector<void>>::value

行为符合预期,但我想知道是否还有更好的方法,例如

IsInstanceOf<std::vector<float>, std::vector<>>::value 
// since this is illegal
IsInstanceOf<std::vector<float>, std::vector>::value

Here是指向示例的链接。

1 个答案:

答案 0 :(得分:4)

#include <type_traits>

template <typename T, template <typename...> typename Template>
struct IsInstanceOf : std::false_type {};

template <
      template <typename...> typename Template,
      typename... TArgs>
struct IsInstanceOf<Template<TArgs...>, Template>
    : std::true_type {};

#include <vector>
static_assert(IsInstanceOf<std::vector<float>, std::vector>::value);
static_assert(!IsInstanceOf<int, std::vector>::value);
#include <string>
static_assert(!IsInstanceOf<std::string, std::vector>::value);
static_assert(IsInstanceOf<std::string, std::basic_string>::value);

int main() {}

https://wandbox.org/permlink/PTXl0KoxoJ2aFJfK