Function template as a parameter to a class template

<> - read this as a template;

I can do this:

void f() {}

//Here I'm declaring a fnc as a <> param
template<void (*fnc)()>
struct Factor { };

int main()
{
  Factor<f> fac;
  return 0;
}

but I cannot do this:

#include <sstream>

template<class R, class T>
R make_(T first, T second)
{
    std::stringstream interpreter;
    R result = R();
    interpreter << first << '.' << second;
    interpreter >> result;
    return result;
}

//Here I'm (trying) to declare fnc <> as a <> param
template<template<class T,class R> R (*fnc)(T,T)>
struct Factor { };

int main(int argc, char* argv[])
{
  Factor<make_> fac;
  return 0;
}

The BIG Q is: How (if possible) can I declare as a template parameter a fnc template?

Edit

Providing that I've used Armen's advise: I would like to be able to do something like this (in main):

Factor<f<"1","02">> m;

Then in m I could make a double type out of those args ("1", "02")

Upvotes: 1

Views: 317

Answers (3)

JoshD
JoshD

Reputation: 12824

Your syntax has some issues. What you do at the end with Factor<make_> fac; is similar to declaring vector<map> v; You need to provide parameters to the template to make it concrete: Factor<make_<int,int> > fac;. But that isn't the whole issue; there are many.

What you're doing with your function isn't quite right. You are providing a specific function (f in the first example), which can be done as a constructor parameter. You should reevaluate your design.

Upvotes: 1

sbi
sbi

Reputation: 224159

From looking at your make_() function template, it seems that what you actually want is boost::lexical_cast<>(). It does what your make_() does, only better. (For starters, your conversion doesn't check for errors at all.)

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133102

There is no syntax for that in C++. What you should do is instead of function template use functor template, which would fit as a template template parameter.

E.G.

template <class R, class T>
struct f
{
    R operator () (T const&)
    {
        //blah
    }
};

template <template<class R, class T> class F >
struct foo
{
    ///...
};

int main()
{
    foo<f> d;
}

Upvotes: 1

Related Questions