简体   繁体   中英

C++ Templates as arguments for templates

I ran into the following problem. I have the following template Number :

template<int n>
struct Number
{
    static const int value = n;
};

Suppose now that I want to add two such Numbers at compile time. Specifically, I want to get the following snippet to work:

//The following code should display 7:
std::cout << Number_add< Number<3>, Number<4> >::value << std::endl;

I tried something like this, but my compiler doesn't like it.

template<Number<int> n1, Number<int> n2>
struct Number_add
{
    static const int value = n1::value + n2::value;
}

What is the correct way to implement Number_add? I think that template template parameters might be needed here, but I couldn't get that to work either. Help would be greatly appreciated.

Number<int> cannot be used as a non-type template parameter because User defined classes aren't one of the allowed types. The allowed types are (reproduced from cppreference.com ):

  • std::nullptr_t (since C++11);
  • integral type;
  • lvalue reference type (to object or to function);
  • pointer type (to object or to function);
  • pointer to member type (to member object or to member function);
  • enumeration type.

You can simply do as nm suggested in the comments

template<typename n1, typename n2>
struct Number_add
{
    static const int value = n1::value + n2::value;
}
template<int A, int B>
constexpr Number<A+B>
operator+(Number<A>, Number<B> ){ return {}; }

template<class Lhs, class Rhs>
using Number_add=decltype(Lhs{}+Rhs{});

std::cout << Number_add< Number<3>, Number<4> >::value << std::end;

Prints 7.

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