I was wondering if it was possible to have nested C++ template and still be able to access the template values ?
To explain, here is what I currently have:
template <int first, int... tail>
struct ConstIntVector:ConstIntVector<tail...>
{};
template <int first>
struct ConstIntVector<first>
{};
template<int f1, int... t1>
int prod(const ConstIntVector<f1, t1...>, const int* a) {
return f1 * (*a) + prod(ConstIntVector<t1...>(), a+1);
}
This way, I can access the f1 value in my prod function. But I would like to do it like this:
template<ConstIntVector<int f1, int... t1>>
int prod(const int* a) {
return f1 * (*a) + prod<ConstIntVector<t1...>>(a+1);
}
It is possible ?
Partial template specializations aren't allowed for member functions. But you can use a helper struct:
namespace detail
{
template <typename T>
struct prodHelper;
template <int f1, int... t1>
struct prodHelper<ConstIntVector<f1, t1...> >
{
static int eval(const int* a) {
return f1 * (*a) + prodHelper<ConstIntVector<t1...>>::eval(a+1);
}
};
}
template <typename T>
int prod(const int* a) {
return detail::prodHelper<T>::eval(a);
}
Another option would be to utilize ConstIntVector structs to carry useful information:
template <int First, int... Tail>
struct ConstIntVector {
constexpr static int value = First;
using tail = ConstIntVector<Tail...>;
};
template <int First>
struct ConstIntVector<First> {
constexpr static int value = First;
using got_no_tail = void;
};
template <class CIV, typename CIV::tail* = nullptr>
int prod(const int* a) {
return CIV::value * (*a) + prod<typename CIV::tail>(a+1);
}
template <class CIV, typename CIV::got_no_tail* = nullptr>
int prod(const int* a) {
return CIV::value * (*a);
}
Just be aware, that recursion is neither necessary nor desirable to solve these kinds of TMP problems. First, it is better to simply define your vector like this:
template <int... Is>
struct ConstIntVector{};
That way you can have zero length vectors as well, which is convenient in handling edge cases (witness the fact that std::array can be length 0).
Next, lets write our product function. We'll modify it in two ways: first we'll infer the integer by trivially passing our ConstIntVector by value, and second we'll use pack expansions to avoid recursion.
template<int... Is>
int prod(const int* a, ConstIntVector<Is...>) {
int index = 0;
int sum = 0;
int [] temp = {(sum += (a[index++] * Is))...};
return sum;
}
Usage:
std::vector<int> v{1,2,3};
using v2 = ConstIntVector<4,5,6>;
std::cerr << prod(v.data(), v2{});
Live example: http://coliru.stacked-crooked.com/a/968e2f9594c6b292
Link to example of highly optimized assembly: https://godbolt.org/g/oR6rKe.
How about
template<int I>
int prod(const int* a) {
return I * (*a);
}
template<int I, int I2, int... Is>
int prod(const int* a) {
return I * (*a) + prod<I2, Is...>(a + 1);
}
Related
Suppose I want to enable writing this:
template <int a,int b> struct add_base{ static const int value = a+b;};
template<int...a> using add = accumulate<add_base,0,a...>;
template <int a,int b> struct mult_base{ static const int value = a*b;};
template<int...a> using mult = accumulate<mult_base,1,a...>;
template <int a,int b> struct sqsum_base{ static const int value = a+b*b;};
template<int...a> using sqsum = accumulate<sqsum_base,0,a...>;
static_assert( add<1,2,3>::value == 6 );
static_assert( mult<2,2,2>::value == 8 );
static_assert( sqsum<1,2,3>::value == 14 );
My accumulate looks like this:
template <template <int,int> class G,
int first, int second,
int...more>
struct accumulate {
static const int value = accumulate<G,G<first,second>::value,more...>::value;
};
template <template <int,int> class G,
int first, int second>
struct accumulate<G,first,second> {
static const int value = G<first,second>::value;
};
Now I wonder if accumulate can be condensed by expanding the recusion inline, something like:
template <template <int,int> class G,
int first,int second,
int...more>
struct accumulate {
static const int value = G< G<first,second>::value , more...>::value;
};
This is wrong and will result in
error: Wrong number of template arguments (3 should be 2)
Is it possible to unpack the parameters to instantiate G recursively in one line? If not, how to write accumulate without having to write a specialization?
If your compiler has support for C++17 then you may want to utilize fold expression:
template<int ... x_item> struct
accumulate
{
static inline constexpr int const s_value{(0 + ... + x_item)};
};
static_assert(6 == accumulate<1, 2, 3>::s_value);
online compiler
Example of parametrized operation:
template<typename x_Op, int ... x_items> struct
accumulate
{
static inline constexpr int const s_value{(x_Op{0} + ... + x_Op{x_items}).value};
};
struct
sq_sum
{
int value;
};
inline constexpr sq_sum
operator +(sq_sum left, sq_sum right)
{
return sq_sum{left.value + right.value * right.value};
}
static_assert(14 == accumulate<sq_sum, 1, 2, 3>::s_value);
online compiler
Suppose we have function such as
template <typename T, unsigned N> void foo();
and for simplicity assume that we know that only (constant) values N_1, N_2 ... N_k are valid for N.
Now, suppose I want to make that compile-time parameter a run-time one, using foo() as a black-box, i.e. implement:
template <typename T> void foo(unsigned n);
by making foo<,>() calls. How should I go about doing that? Obviously, I can write:
template <typename T> void foo(unsigned n) {
switch(n) {
case N_1 : foo<T, N_1>(); break;
case N_2 : foo<T, N_2>(); break;
// etc. etc.
case N_k : foo<T, N_k>(); break;
}
}
... but this makes me feel all dirty. I could use a MAP() meta-macro to generate these k lines, I suppose; but can I do anything better and less-macroish to achieve the same? Is it possible to write something like the above that's general, and works for every variadic template and a fixed sequence of constant values?
Notes:
C++11/14/17-specific suggestions are obviously welcome.
The N's are not necessarily contiguous, nor small, nor sorted. e.g. suppose N_2 = 123456789 and N_5 = 1.
You could make a function pointer table:
using F = void(*)();
template <class T, class >
struct Table;
template <class T, size_t... Is>
struct Table<T, std::index_sequence<Is...> > {
static constexpr F fns[] = {
foo<T, Is>...
};
};
template <class T, size_t... Is>
constexpr F Table<T, std::index_sequence<Is...> >::fns[sizeof...(Is)];
And then just invoke the one you want:
template <class T, size_t N>
struct MakeTable : Table<T, std::make_index_sequence<N>> { };
template <typename T>
void foo(unsigned n) {
MakeTable<T, MaxN>::fns[n]();
}
If the N_ks aren't contiguous, then we can use a lambda for inline parameter unpacking:
template <class T>
void foo(unsigned n) {
using seq = std::index_sequence<N_1, N_2, ..., N_k>;
indexer(seq)([n](auto i){
if (n == i) {
f<T, i>();
}
});
}
If the above is too slow, then I guess just manually build a std::unordered_map<unsigned, void(*)()> or something.
In these kind of situations I like to build a static table of function pointers, with a dynamic parameter deciding which one to dispatch to. Below is an implementation that achieves this, in the function foo_dynamic. To this function, you specify the maximum value of N you'd like to support, and it builds a static table of function pointers using some recursive templates. You then dereference into this table with your dynamic parameter.
using ftype = void (*)();
template <typename T, unsigned N> void foo()
{
std::cout << N << std::endl;
}
template <typename T, unsigned max>
struct TablePopulator
{
static void populateFTable(ftype* table)
{
table[max] = foo<T,max>;
TablePopulator<T,max-1>::populateFTable(table);
}
};
template <typename T>
struct TablePopulator<T, 0>
{
static void populateFTable(ftype* table)
{
table[0] = foo<T,0>;
}
};
template<typename T, unsigned max_N>
std::array<ftype, max_N>& initTable()
{
static std::array<ftype, max_N> table;
TablePopulator<T, max_N-1>::populateFTable(table.data());
return table;
}
template<typename T, unsigned max_N>
void foo_dynamic(unsigned actualN)
{
static auto ftable = initTable<T, max_N>();
if(actualN >= max_N)
throw std::runtime_error("Max param exceeded");
ftable[actualN]();
}
int main()
{
foo_dynamic<int, 10>(1);
foo_dynamic<int, 10>(5);
return 0;
}
EDIT: Given the constraints in the question edit, here's an approach where valid indices are specified manually, which uses an unordered_map instead of an array:
using ftype = void (*)();
template <typename T, unsigned N> void foo()
{
std::cout << N << std::endl;
}
template<typename T, size_t ... Indices>
void foo_dynamic_indices(size_t actual_index)
{
static std::unordered_map<size_t, ftype> fmap = {{Indices, foo<T,Indices>}...};
auto fIt = fmap.find(actual_index);
if(fIt == fmap.end())
throw std::runtime_error("Index not found");
fIt->second();
}
int main()
{
foo_dynamic_indices<int, 0, 3, 400, 1021, 10000000>(10000000);
foo_dynamic_indices<int, 0, 3, 400, 1021, 10000000>(4); //Exception
return 0;
}
For example, I have a class:
class A
{
enum {N = 5};
double mVariable;
template<class T, int i>
void f(T& t)
{
g(mVariable); // call some function using mVariable.
f<T, i+1>(t); // go to next loop
}
template<class T>
void f<T, N>(T& t)
{} // stop loop when hit N.
};
Partial specialization is not allowed in function template. How do I work around it in my case?
I slightly changed the example of Arne Mertz, like:
template<int n>
struct A
{
enum {N = n};
...
};
and use A like:
A<5> a;
The I cannot compile on Visual Studio 2012. Is it a compiler bug or something else? It is quite strange.
EDIT: Checked. It is a Visual Studio bug. :(
I think Nim gives the most simple way to implement it.
The most straight forward solution is to use a template class instead of a function:
class A
{
enum {N = 5};
double mVariable;
template <class T, int i>
struct fImpl {
static_assert(i<N, "i must be equal to or less than N!");
static void call(T& t, A& a) {
g(a.mVariable);
fImpl<T, i+1>::call(t, a);
}
};
template<class T>
struct fImpl<T,N> {
static void call(T&, A&) {} // stop loop when hit N.
};
public:
template<class T, int i>
void f(T& t)
{
fImpl<T, i>::call(t,*this);
}
};
Example link
You can define a helper class:
template <int i, int M>
struct inc_up_to
{
static const int value = i + 1;
};
template <int i>
struct inc_up_to<i, i>
{
static const int value = i;
};
template<class T, int i>
void f(T& t)
{
if (i < N) {
g(mVariable); // call some function using mVariable.
f<T, inc_up_to<i, N>::value>(t);
}
}
It stops the compile-time recursion by making f<T, N> refer to f<T, N>, but that call is avoided by the run-time condition, breaking the loop.
A simplified and more robust version of the helper (thanks #ArneMertz) is also possible:
template <int i, int M>
struct inc_up_to
{
static const int value = (i >= M ? M : i + 1); // this caps at M
// or this:
static const int value = (i >= M ? i : i + 1); // this leaves i >= M unaffected
};
This doesn't even need the partial specialisation.
With c++11 support, you can do the following:
#include <iostream>
#include <type_traits>
using namespace std;
struct A
{
enum {N = 5};
double mVariable;
void g(int i, double v)
{ std::cout << i << " " << v << std::endl; }
template<int i, class T>
typename enable_if<i >= N>::type f(T& t)
{} // stop loop when hit N.
template<int i, class T>
typename enable_if<i < N>::type f(T& t)
{
g(i, mVariable); // call some function using mVariable.
f<i+1, T>(t); // go to next loop
}
};
int main(void)
{
A a;
int v = 0;
a.f<0>(v);
}
Main reason I like is that you don't need any of the cruft as required by the previous answers...
You can emulate partial specialization of function template with function overloading:
#include <type_traits>
class A
{
enum {N = 5};
double mVariable;
// ...
void g(double)
{
// ...
}
public:
template<class T, int i = 0>
void f(T& t, std::integral_constant<int, i> = std::integral_constant<int, i>())
{
g(mVariable);
f(t, std::integral_constant<int, i + 1>());
}
template<class T>
void f(T& t, std::integral_constant<int, N>)
{
}
};
Example of using:
A a;
int t = 0;
a.f(t);
a.f(t, std::integral_constant<int, 2>()); // if you want to start loop from 2, not from 0
It is a C++11 solution, however (not so much because of std::integral_constant class, but because of default template parameter of function template). It can be made shorter using some additional C++11 features:
template<int i>
using integer = std::integral_constant<int, i>;
template<class T, int i = 0>
void f(T& t, integer<i> = {})
{
g(mVariable);
f(t, integer<i + 1>());
}
template<class T>
void f(T& t, integer<N>)
{
}
Consider the following metafunction for an integral pow (it is just an example) :
class Meta
{
template<int N, typename T> static constexpr T ipow(T x)
{
return (N > 0) ? (x*ipow<N-1>(x))
: ((N < 0) ? (static_cast<T>(1)/ipow<N>(x))
: (1))
}
};
How to write the stop condition for such a function ?
Anytime you ask yourself "how to simulate partial specialization for functions", you can think "overload, and let partial ordering decide what overload is more specialized".
template<int N>
using int_ = std::integral_constant<int, N>;
class Meta
{
template<int N, typename T> static constexpr T ipow(T x)
{
return ipow<N, T>(x, int_<(N < 0) ? -1 : N>());
}
template<int N, typename T> static constexpr T ipow(T x, int_<-1>)
{
// (-N) ??
return static_cast<T>(1) / ipow<-N>(x, int_<-N>());
}
template<int N, typename T> static constexpr T ipow(T x, int_<N>)
{
return x * ipow<N-1>(x, int_<N-1>());
}
template<int N, typename T> static constexpr T ipow(T x, int_<0>)
{
return 1;
}
};
I think you wanted to pass -N instead of N at the comment-marked position.
A simple version might go like this:
template <typename T, unsigned int N> struct pow_class
{
static constexpr T power(T n) { return n * pow_class<T, N - 1>::power(n); }
};
template <typename T> struct pow_class<T, 0>
{
static constexpr T power(T) { return 1; }
};
template <unsigned int N, typename T> constexpr T static_power(T n)
{
return pow_class<T, N>::power(n);
}
Usage:
auto p = static_power<5>(2); // 32
Just use static members in a class template and specialize the class template. You might want to create a forwarding function template for convenience, though.
I am looking for a way to optionally include members of a c++ class to generate POD structs. I found that this works fairly well, but is nonstandard:
#include <iostream>
template <int v, int n, int t>
struct Point
{
int vertex[v];
float normal[n];
double texcoord[t];
};
int main()
{
std::cout << (sizeof (Point<0,0,1>)) << std::endl;
std::cout << (sizeof (Point<1,0,1>)) << std::endl;
std::cout << (sizeof (Point<1,1,2>)) << std::endl;
std::cout << (sizeof (Point<0,0,0>)) << std::endl;
return 0;
}
So Point<1,0,0> would only contain a vertex (the int type will actually be a vector3 type in practice), and so on. The main reason for this is to easily support interleaved arrays for OpenGL.
Maybe try something like this:
#include <type_traits>
template <unsigned int v, unsigned int n, unsigned int t>
struct Point
{
int data[v + n + t];
template <unsigned int i>
typename std::enable_if<(i < v), int &>::type
vertex() { return data[i]; }
template <unsigned int i>
typename std::enable_if<(i < v + n), int &>::type
normal() { return data[v + i]; }
template <unsigned int i>
typename std::enable_if<(i < v + n + t), int &>::type
texcoord() { return data[v + n + i]; }
};
Usage:
Point<1,1,2> p;
p.vertex<0>() = 50;
std::array<T, 0> is valid, unlike T[0] and really is a better solution all around. Unfortunately, and since this is only available for C++11, I can't figure out if its Boost namesake boost::array also has such support.
It is also possible to write an array-like helper yourself.
You can do this, but you would need specializations.
Edit: Matched with new question requirement of different type per array. Made template arguments unsigned though.
template <> struct Point<0, 0, 0> {};
template <unsigned v> struct Point<v, 0, 0> { int vertex[v]; };
template <unsigned n> struct Point<0, n, 0> { float normal[n]; };
template <unsigned t> struct Point<0, 0, t> { double texcoord[t]; };
template <unsigned v, unsigned n> struct Point<v, n, 0> {
int vertex[v];
float normal[n];
};
template <unsigned v, unsigned t> struct Point<v, 0, t> {
int vertex[v];
double texcoord[t];
};
template <unsigned n, unsigned t> struct Point<0, n, t> {
float normal[n];
double texcoord[t];
};
Each specialization leaves out the associated array when its corresponding template parameter has value 0. For three items as shown, the enumeration of specializations is not overly large, and provides exactly the same syntax for accessing the elements as your original post but using standard C++ constructs.
Extending this technique beyond 3 arrays would be cumbersome. However, it could be managed with a script to generate the specializations for you.