C++模板传入一个模板化的class,后面指定模板类型

C++ templates pass in a templated class and specify the template type later

我想做类似下面的事情

#include <iostream>
#include <functional>
using namespace std;

bool b1, b2;
int i1, i2;

template<typename COMP>
bool my_comp(COMP comp)
{
    return comp<bool>(b1, b2) && comp<int>(i1, i2);
}

int main() 
{
    my_comp(std::equal_to);
    return 0;
}

例如,我想将模板化 class 传递给模板并在事后指定模板化 classes 模板参数。

我可以这样做吗?

是的,这可以通过使用模板模板参数使用稍微不同的语法实现:

#include <iostream>
#include <functional>
using namespace std;

bool b1, b2;
int i1, i2;

template<template <class T> class COMP>
bool my_comp()
{
    return COMP<bool>{}(b1, b2) && COMP<int>{}(i1, i2);
}

int main()
{
    my_comp<std::equal_to>();
    return 0;
}