简体   繁体   中英

Non-type Templates for policy functions

So, I am trying to use a policy which in turn has a non-type templated function. The compiler is having some issues figuring out what I am trying to do.

For example, one policy looks like:

template <int unsigned NBits> struct Foo {

/* Internal data type that provides NBits of storage */
typedef int unsigned DataType; // for  example

/* Accessor */
template <int unsigned QueryBit>
bool const IsBitSet(DataType const &) const { /* ... */ }

};

The other policy uses this one to perform a series of operations on the bits that are set:

template <typename FooPolicy> struct DoBar_WithFoo {

FooPolicy FooPolicy_;

bool const XOR_SpecificBits(FooPolicy::DataType const &Data) const {
  // Error listed below points to this line
  return FooPolicy_.IsBitSet<10>(Data) ^ FooPolicy_.IsBitSet<8>(Data) /* ... */ ;
}

};

The user class requires a Foo policy as well as a Bar policy:

template<typename FooPolicy, typename DoBar_Policy> struct UserClass {

  // Use FooPolicy for data

  void MyFunction() {
    // Use DoBar_Policy to manipulate data
  }
};

The user combines the two above as follows:

typedef Foo<12> Foo_12Bits_type;
typedef DoBar_WithFoo<Foo_12Bits_Type> Bar_type;

typedef UserCLass<Foo_12Bits_type, Bar_type> MyUserClass;

MyUserClass.MyFunction();

I get an error as follows:

error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'

This error points to the following bit of code (as commented above):

/* ... */ FooPolicy_.IsBitSet<10>(Data) /* ... */

What I can deduce from this is that the <10> looks like a comparison operation. But, I am really asking the compiler to specialize the template function contained in the policy.

Can I do this? How do I go about doing this?

If anyone is wondering, I am trying to write an LFSR. I would like to move to a different underlying data type in the future, and also keep the specific polynomial used to generate the LFSR separate from the data type and operations used to store and manipulate the LFSR bits.

Thanks in advance!

You need to disambiguate the call to the nested function template by inserting the template keyword just prior to the member's name:

bool const XOR_SpecificBits(FooPolicy::DataType const &Data) const {
  // Error listed below points to this line
  return FooPolicy_.template IsBitSet<10>(Data) ^ FooPolicy_.template IsBitSet<8>(Data) /* ... */ ;
                    ^^^^^^^^                                 ^^^^^^^^
}

For why this has to be done, see this famous Q&A .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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