Vitali
Vitali

Reputation: 321

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.

Can I do this?

Upvotes: 1

Views: 830

Answers (1)

MikeMB
MikeMB

Reputation: 21156

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

Upvotes: 5

Related Questions