c++ - 将类模板作为模板参数传递

标签 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是示例的链接。

最佳答案

#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

关于c++ - 将类模板作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53796754/

相关文章:

c++ - 将数组的元素设置为等于整个数组c++

c++ - 数组值自动更改为 0

c++ - C++ 17 可以处理嵌套的可变参数模板吗?

c++ - 有没有什么方法可以在没有 std::move 的情况下调用 C++ 中的移动赋值运算符?

c++ - 引用初始化和常量表达式

c++ - 如何生成 N 类型 T 的元组?

c++ - delete[] 如何跟踪元素的数量?

c++ - 简化可变参数模板 : Remove some specializations

c++ - 多维 std::intializer_list,其中维数指定为其类的模板参数

c++ - 使用虚拟析构函数会使非虚拟函数进行 v 表查找吗?