lightxbulb
lightxbulb

Reputation: 1321

C++ Hide template parameters

I don't know if this is possible at all, but I would like to "hide" some template parameters from a given class. Here's what I mean, say I have the following code:

template<class A, int b>
class Foo
{
};
template<template<class,int> class Foo_specialized, class A, int b>
class Bar
{
    Foo_specialized<A,b> obj;
};

Now supposed Bar does not need to know about A, but needs to know about b. Naturally something like this would be perfect (the following is a pseudo code just to illustrate the idea):

template<template<int> class Foo_specialized_by_first_parameter, int b>
class Bar
{
    Foo_specialized_by_first_parameter<b> obj;
};

I'm not really sure if that's possible at all, the idea would be to have something like this when instancing Bar:

Bar<Foo<float>, 5> bar_instance;

Of course this does not work because Foo doesn't accept 1 parameter. Basically I need something like (Foo<float>)<5> to be possible. The closest thing I can think of is currying in haskell.

Upvotes: 2

Views: 1362

Answers (2)

lorro
lorro

Reputation: 10880

Assuming for a second that you can change that int to std::integral_constant:

#include <iostream>
#include <string>
#include <map>

template<template<typename...> typename T, typename H>
struct Bind1st
{
    template<typename... Arg>
    using type = T<H, Arg...>;
};

int main() {
    // to bind it
    Bind1st< std::map, std::string >::type< std::string > mymap;
    mymap[ "a" ] = "b";
}

Naturally, Bar< Bind1st< Foo, float >::type, 5 > should also work.

Upvotes: 1

Jarod42
Jarod42

Reputation: 217245

You may use template typedef:

template <int N>
using Foo_float = Foo<float, N>;

And then, with

template <template<int> class Foo_specialized_by_first_parameter, int b>
class Bar
{
    Foo_specialized_by_first_parameter<b> obj;
};

you may do:

Bar<Foo_float, 5> bar_instance;

Upvotes: 5

Related Questions