简体   繁体   English

C ++模板传入模板化类,并在以后指定模板类型

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

I want to do something like the following 我想做以下事情

#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;
}

As in, I want to pass a templated class to a template and specify the templated classes template argument after the fact. 与之类似,我想将模板化类传递给模板,然后在事实之后指定模板化类template参数。

Can I do this? 我可以这样做吗?

Yes, this is possible with a slightly different syntax by using template template parameters : 是的,这可以通过使用模板模板参数以稍微不同的语法实现:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM