JuliaInterop / CxxWrap.jl

Package to make C++ libraries available in Julia
Other
416 stars 67 forks source link

How to wrap template classes with non-type parameters? #95

Open philtomson opened 6 years ago

philtomson commented 6 years ago

I'm wondering if there is currently a way to wrap a templated struct like this where the template params are not types:

template< uint8_t WWIDTH, uint8_t FRACWIDTH>
struct FixedPt {

      using FP = FixedPt< WWIDTH, FRACWIDTH>;
      constexpr static const int MAX_VAL = (1 << (WWIDTH+FRACWIDTH))-1;
      uint64_t val_    : (WWIDTH + FRACWIDTH);

      uint8_t wwidth(){
         return WWIDTH;
      }

      uint8_t fracwidth(){
         return FRACWIDTH;
      }

      int max_val() {
         constexpr const int max_val_ = (1<<(WWIDTH+FRACWIDTH))-1;
         return (max_val_);
      }
      //constructors ....
};

The template example in the README.md shows:

types.add_type<Parametric<TypeVar<1>, TypeVar<2>>>("TemplateType")

How would one go about specifying that the parameters there aren't types, but values?

barche commented 6 years ago

The trick is to specialize jlcxx::BuildParameterList, there is an example for this in https://github.com/JuliaInterop/CxxWrap.jl/blob/master/deps/src/jlcxx/examples/parametric.cpp for the type NonTypeParam.

philtomson commented 6 years ago

I notice in that example, though, that they specify the non-type values in the wrapping:

types.add_type<Parametric<jlcxx::TypeVar<1>, jlcxx::TypeVar<2>>>("NonTypeParam")
.apply<NonTypeParam<int, 1>, NonTypeParam<unsigned int, 2>, NonTypeParam<int64_t, 64>>(WrapNonTypeParam());

So they supply the values 1, 2 and 64 to NonTypeParam.

In my case, I'd like to be able to supply those parameters on the Julia side. I'd like to be able to do something like this on the Julia side:

foo = FixedPt{5,3}(8.2)

Is it possible?

barche commented 6 years ago

It's possible, but you do need to enumerate all the allowed template parameter values in the C++ files. If you need truly on-the-fly compilation of C++ templates based on parameters passed from Julia, Cxx.jl is a better fit for the problem.