Best Way to Create N Objects at Compile Time - c++

I wondered how you would go about creating N objects at compile time with templates. Or this was indeed even good practise.
I have a header file containing some constants:
constexpr size_t N_TIMES = 3;
constexpr uint32_t MIN[N_TIMES] = {0,1,2};
constexpr uint32_t MAX[N_TIMES] = {1,2,3};
Then a header file containing a template which will be generate "N" times:
template <typename T>
class foo
{
public:
foo(uint32_t min , uint32_t max) :
min(min),
max(max)
{
std::cout << "I was created with " << min << " " << max << std::endl;
}
private:
const uint32_t min;
const uint32_t max;
};
The part I'm a little unsure about is I have:
template <typename T>
class bar
{
public:
bar()
{
for(auto i = 0; i < N_TIMES; i ++)
{
foo_[i] = foo<T>(MIN[i], MAX[i]);
}
}
private:
std::array<foo<T>, N_TIMES> foo_;
};
I currently get the error:
cannot be assigned because its copy assignment operator is implicitly deleted
But since it's in the constructor, it'll generate this after compiling anyway. So really I was just wondering how I should be going about this instead. If there was some kind of clever recursive trick I could pull to create these objects for me at compile time.

You may use std::index_sequence:
namespace detail
{
template <typename T, std::size_t N, std::size_t...Is>
std::array<Foo<T>, N> make_foo_array(std::index_sequence<Is...>)
{
return {{Foo<T>(MIN[Is], MAX[Is])...}};
}
}
template <typename T, std::size_t N>
std::array<Foo<T>, N> make_foo_array()
{
return detail::make_foo_array<T, N>(std::make_index_sequence<N>{});
}
And then
template <typename T>
class bar
{
public:
bar() : foo_(make_foo_array<T, N_TIMES>()) {}
private:
std::array<foo<T>, N_TIMES> foo_;
};

Related

Enable Different Member Functions Depending On If Type Is POD

I believe this is fairly simply to achieve, but I can't figure out how.
Take the following example class:
class Example {
public:
template <typename T>
size_t foo(T& v) const;
};
How can I provide two implementations for this method depending on if T is a POD? I know there is an std::is_pod type trait, but I can't figure out how to have it enable the correct function.
I also need to be able to provide specific specializations for certain types of T regardless of if they are PODs or not. For example, I want to be able to write:
template <>
size_t foo<uint8_t>(uint8_t& b);
While all other types of T are chosen based upon being PODs or not.
EDIT
I have been looking at the information everyone has been giving and have come up with the following, however, this still does not work (throws a compiler error). I can't understand why.
class Example {
public:
template <typename T, bool U = std::is_trivially_copyable<T>::value>
size_t foo(T& v) const;
};
template <typename T>
size_t Example::foo<T, true>(T& v) const {
//Do something if T is mem copyable
}
template <typename T>
size_t Example::foo<T, false>(T& v) const {
//Do something if T is not mem copyable
}
Which results in "non-class, non-variable partial specialization 'foo<T, true>' is not allowed"
You can do it in the following way.
#include <iostream>
#include <type_traits>
struct A {
int m;
};
struct B {
int m1;
private:
int m2;
};
struct C {
virtual void foo() {};
};
// is_pod is deprecated since C++ 20
template <typename T>
std::enable_if_t<std::is_pod_v<T>, size_t> foo(const T& pod)
{
std::cout << &pod << " is_pod\n";
return 0;
}
template <>
size_t foo<uint8_t>(const uint8_t& b)
{
std::cout << int(b) << " is uint8_t\n";
return 1;
}
template <>
size_t foo<int>(const int& b)
{
std::cout << int(b) << " is int\n";
return 1;
}
int main()
{
uint8_t a = 2;
foo(a);
foo(22);
// will compile
A instance;
foo(instance);
// will not compile
B b;
//foo(b);
// will not compile
C c;
//foo(c);
}
output
2 is uint8_t
22 is int
010FFA64 is_pod
Here is what I did to get it to work correctly:
#include <type_traits>
#include <iostream>
class Example {
public:
Example(int a) : _a(a) {}
virtual void bar() {}
template <typename T, typename std::enable_if<std::is_trivially_copyable<T>::value, size_t>::type = 0>
size_t foo(T& v) const {
std::cout << "T is trivially copyable" << std::endl;
return sizeof(T);
}
template <typename T, typename std::enable_if<!std::is_trivially_copyable<T>::value, size_t>::type = 0>
size_t foo(T& v) const {
std::cout << "T is not trivially copyable" << std::endl;
return sizeof(T);
}
private:
int _a;
int _b;
int _c;
};
template <>
size_t Example::foo<unsigned int>(unsigned int& v) const {
std::cout << "T is unsigned int" << std::endl;
return sizeof(unsigned int);
}
int main() {
Example e(10);
int a;
e.foo(a);
char b;
e.foo(b);
e.foo(e);
unsigned int c;
e.foo(c);
return 0;
}
The output of which looks like:
T is trivially copyable
T is trivially copyable
T is not trivially copyable
T is unsigned int
This is based upon the following Provide/enable method to in a class based on the template type

Compile time creation of class member stl container (const std::array) filled with elements

I tried to create a minimal example as it is possible with templates.
(MSVC15, c++14)
There are 2 questions may be connected with each other.
Question 1: Is it possible to create at compile time container class member (for example std::array) filled with elements?
_limited_int_ptr_container _intIndexes
{
// _startIntIndex
// create indexes???
std::make_shared<_limited_int_>(_startIntIndex), // 10060u _startStrIndex
//std::make_shared<_limited_int_>(_startIntIndex + 1),
//std::make_shared<_limited_int_>(_startIntIndex + 2),
//...
std::make_shared<_limited_int_>(_startIntIndex + _maxIntIndexes -1)
};
Question 2: Is it possible to combine several template classes with one general template parameter but only once?
template <class T, size_t Size>
using _container = const std::array<T, Size>;
template <class T>
using _ptr = std::shared_ptr<T>;
// is it possible to combine this 2 types and use _maxStrIndexes only once?
using _limited_str_ = IndexStr<_maxStrIndexes>;
using _limited_str_ptr = _ptr<_limited_str_>;
using _limited_str_ptr_container = _container<_limited_str_ptr, _maxStrIndexes>;
Full code:
#include <iostream>
#include <memory>
#include <array>
template<class T, size_t MaxIndex>
class BaseIndex
{
public:
virtual ~BaseIndex() = default;
explicit BaseIndex(const size_t index)
: _maxIndex(MaxIndex), _currentIndex(index) {}
virtual void DoSmth() = 0;
friend std::ostream & operator << (std::ostream & ss, BaseIndex & base_index)
{
ss << "Max: " << base_index._maxIndex << ". Current: " << base_index._currentIndex << std::endl;
return ss;
}
protected:
const size_t _maxIndex;
size_t _currentIndex{ 0u };
};
template<size_t MaxIndex>
class IndexStr : public BaseIndex<std::string, MaxIndex>
{
public:
explicit IndexStr(const size_t index) :BaseIndex(index) {}
void DoSmth() override { std::cout << IndexStr::_maxIndex; }
};
template<size_t MaxIndex>
class IndexInt :public BaseIndex<int, MaxIndex>
{
public:
explicit IndexInt(const size_t index) :BaseIndex(index) {}
void DoSmth() override { std::cout << IndexInt::_maxIndex; }
};
class Manager
{
private:
static const size_t _startStrIndex{ 11u };
static const size_t _startIntIndex{ 10060u };
static const size_t _maxStrIndexes{ 5 };
static const size_t _maxIntIndexes{ 120 };
public:
template <class T, size_t Size>
using _container = const std::array<T, Size>;
template <class T>
using _ptr = std::shared_ptr<T>;
// is it possible to combine this 2 types and use _maxStrIndexes only once?
using _limited_str_ = IndexStr<_maxStrIndexes>;
using _limited_str_ptr = _ptr<_limited_str_>;
using _limited_str_ptr_container = _container<_limited_str_ptr, _maxStrIndexes>;
// const std::array<std::shared_ptr<IndexStr<_maxStrIndexes>>, _maxStrIndexes> _strIndexes
_limited_str_ptr_container _strIndexes
{
// _startStrIndex
// create indexes ???
// std::integer_sequence ???
std::make_shared<_limited_str_>(_startStrIndex), // 11 = _startStrIndex
std::make_shared<_limited_str_>(12),
std::make_shared<_limited_str_>(13),
std::make_shared<_limited_str_>(14),
std::make_shared<_limited_str_>(_startStrIndex + _maxStrIndexes - 1)
};
// is it possible to combine this 2 types and use _maxIntIndexes only once?
using _limited_int_ = IndexInt<_maxIntIndexes>;
using _limited_int_ptr = _ptr<_limited_int_>;
using _limited_int_ptr_container = _container<_limited_int_ptr, _maxIntIndexes>;
_limited_int_ptr_container _intIndexes
{
// _startIntIndex
// create indexes???
std::make_shared<_limited_int_>(_startIntIndex), // 10060u _startStrIndex
//...
std::make_shared<_limited_int_>(_startIntIndex + _maxIntIndexes -1)
};
};
template <class T, size_t Size >
void Process(const std::array<std::shared_ptr<T>, Size> _array)
{
for (auto &&baseindex : _array)
std::cout << *baseindex;
}
int main()
{
Manager m;
Process(m._strIndexes);
//Process(m._intIndexes);
return 0;
}
Live demo
About the first question: yes, it is possible. It is even quite easy provided that you can use C++11 and variadic templates.
To generate a compile-time list of indices, you can use std::make_index_sequence<N>, which will return a std::index_sequence<0, 1, 2, 3, ..., N-1>. You can then pattern-match it with the function creating the compile-time array:
template <std::size_t... Ns>
constexpr auto fill_it_at_compile_time_impl(std::index_sequence<Ns...>) {
return std::array<unsigned, sizeof...(Ns)>{ Ns... };
}
template <std::size_t N>
constexpr auto fill_it_at_compile_time() {
return fill_it_at_compile_time_impl(std::make_index_sequence<N>());
}
If you want to add an offset to the index_sequence members, just do so in the array initialization:
constexpr auto offset = 10u;
template <std::size_t... Ns>
constexpr auto fill_it_at_compile_time_impl(std::index_sequence<Ns...>) {
return std::array<unsigned, sizeof...(Ns)>{ (offset+Ns)... };
}
About the second question:
As far as I understand it, yes, it's possible. First, create a helper struct to query the index of _limited_str:
template <typename T>
struct query_max_index;
template <std::size_t N>
struct query_max_index<IndexStr<N>> {
static const auto max_index = N;
};
Then, rather than refering to _maxStrIndexes directly, you can query it from indirectly from _limited_str_ptr:
using _limited_str_ = IndexStr<_maxStrIndexes>;
using _limited_str_ptr = _ptr<_limited_str_>;
using _limited_str_ptr_container = _container<_limited_str_ptr, query_max_index<std::decay_t<decltype(*std::declval<_limited_str_ptr>())>>::max_index>;

C++ Alternating between two variables at compile time

Suppose you have a class that operates on a vector:
class Foo{
public:
Foo() {
m_dynamic_data.push_back(5);
std::cout << m_dynamic_data[0] << std::endl;
}
private:
std::vector<int> m_dynamic_data;
};
In my case this class is huge with 2500 additional lines of code.
This class behaves dynamic (hence std::vector). But I would also like to provide a "static" implementation (using std::array). So std::size_t N is added, which now should control when to use which attribute.
template<std::size_t N>
class Foo{
private:
std::vector<int> m_dynamic_data; //use this, when N == 0
std::array<int, N> m_static_data; //use this, when N != 0
};
I am not sure if I can get this to work. using #define won't do the job (since it can't alternate). constexpr can't be wrapped around two attributes either. The best solution is probably to provide a base class and then inherit the dynamic and static case from it. But before I spent the next days doing this, I wonder if there isn't a technique afterall.
I thought about putting both into a std::unique_ptr and only constructing the relevant array:
template<std::size_t N>
class Foo {
public:
Foo() {
if constexpr (N) {
m_static_data_ptr = std::make_unique<std::array<int, N>>();
(*m_static_data_ptr)[0] = 5;
std::cout << (*m_static_data_ptr)[0] << std::endl;
}
else {
m_dynamic_data_ptr = std::make_unique<std::vector<int>>(1);
(*m_dynamic_data_ptr)[0] = 5;
std::cout << (*m_dynamic_data_ptr)[0] << std::endl;
}
}
private:
std::unique_ptr<std::vector<int>> m_dynamic_data_ptr;
std::unique_ptr<std::array<int, N>> m_static_data_ptr;
};
I earlier asked about this case here. But apparently this doesn't seem like a good approach. (fragmenting memory, cache miss rate). std::optional also seems interesting, but it pushes the sizeof(Foo) too far for my goal.
Ultimately there is also using void pointers:
template<std::size_t N>
class Foo {
public:
Foo() {
if constexpr (N) {
m_data = malloc(sizeof(std::array<int, N>));
(*static_cast<std::array<int, N>*>(m_data))[0] = 5;
std::cout << (*static_cast<std::array<int, N>*>(m_data))[0] << std::endl;
}
else {
m_data = new std::vector<int>;
(*static_cast<std::vector<int>*>(m_data)).push_back(5);
std::cout << (*static_cast<std::vector<int>*>(m_data))[0] << std::endl;
}
}
~Foo() {
delete[] m_data;
}
private:
void* m_data;
};
But this seems pretty dirty [...]
So the goal would be to work with either array structure at compile time. Thanks for any help / suggestion!
You can abstract the data part of Foo to another class template.
template<std::size_t N> struct FooData
{
std::array<int, N> container;
}
template <> struct FooData<0>
{
std::vector<int> container;
}
template<std::size_t N>
class Foo{
private:
using DataType = FooData<N>;
DataType data;
};
You have to add member functions to FooData to support additional abstractions. The number of such functions and their interface depends on how differently you use the containers in Foo.
R Sahu's answer is great, but you don't need to access the container indirectly through a struct.
template<std::size_t N>
struct FooData { using type = std::array<int, N>;};
template <>
struct FooData<0> { using type = std::vector<int>; };
template<std::size_t N>
using FooData_t = typename FooData<N>::type;
template<std::size_t N>
class Foo{
private:
FooData_t<N> data;
};
Alternatively, you can also use std::conditional_t:
template<std::size_t N>
class Foo{
private:
std::conditional_t<N==0, std::vector<int>, std::array<int, N>> data;
};
You may want to isolate this dynamic/static "morphing" from the rest of your giant 2500-lines Foo class. I can imagine a tiny wrapper around std::array to mimic the interface of std::vector. It can be used as a member of Foo. If the static capacity is set to the sentinel value 0, then it can be specialized to just derive from a real std::vector:
#include <cassert>
#include <cstddef>
#include <array>
#include <iostream>
#include <vector>
template<class value_type_, std::size_t capacity_>
struct StaticOrDynamic {
using value_type = value_type_;
static constexpr std::size_t capacity = capacity_;
std::array<value_type, capacity> arr_{};
std::size_t size_{0};
constexpr void push_back(const value_type& x) {
assert(size_ < capacity && "must not exceed capacity");
arr_[size_++] = x;
}
constexpr const value_type_& at(std::size_t i) const {
assert(i < size_ && "must be in [0, size)");
return arr_[i];
}
/* other members etc */
};
template<class value_type_>
struct StaticOrDynamic<value_type_, 0>// specialization for dynamic case
: std::vector<value_type_>
{
using std::vector<value_type_>::vector;
};
template<std::size_t capacity_>
struct Foo {
static constexpr std::size_t capacity = capacity_;
StaticOrDynamic<int, capacity> m_data_{};
Foo() {// static version may be constexpr (without debug output)
m_data_.push_back(5);
std::cout << m_data_.at(0) << std::endl;
}
};
int main() {
Foo<5> static_foo{};
Foo<0> dynamic_foo{};
}
A similar behavior (static/dynamic chosen by a template parameter) is offered in, e.g., the Eigen library. I do not know how it is implemented there.

variadic template only using type parameter

I would like to do something like this:
#include <iostream>
class a {
public:
a() : i(2) {}
template <typename ...ts>
void exec() {
f<ts...>();
std::cout << "a::()" << std::endl;
}
int i;
private:
template <typename t>
void f() {
i += t::i;
}
template <typename t, typename ...ts>
void f() {
f<t>();
f<t, ts...>();
}
};
struct b {
static const int i = -9;
};
struct c {
static const int i = 4;
};
int main()
{
a _a;
_a.exec<b,c>();
std::cout << _a.i << std::endl;
}
The idea is to get the same information from a group of classes, without the need of an object of each class.
Does anyone know if it is possible?
Thanks!
In case Your compiler does not support C++17:
template <typename ...ts>
void f() {
for ( const auto &j : { ts::i... } )
i += j;
}
In C++17, your class would simply be
class a {
public:
a() : i(2) {}
template <typename ...ts>
void exec() {
((i += ts::i), ...); // Folding expression // C++17
std::cout << "a::()" << std::endl;
}
int i;
};
Possible in C++11 too, but more verbose.
Reasons why your code is not compiling:
Syntax of specializing templates is a little different.
You need to put the most general case first.
You can't partially specialize functions, only classes.
Partial specialization is not allowed within classes, only in namespaces.
Here is an example for C++11.
#include <iostream>
template<typename t, typename ...ts>
class a {
public:
static constexpr int x = t::i + a<ts...>::x;
};
template<typename t>
class a<t> {
public:
static constexpr int x = 2 + t::i;
};
struct b {
static constexpr int i = -9;
};
struct c {
static constexpr int i = 4;
};
int main()
{
constexpr int result = a<b,c>::x;
std::cout << result << std::endl;
}
Remember that templates are calculated during compilation so, for optimization sake, it is a good idea to write them in a way that allows them to be constexpr.

Getting value of template parameter from embracing type

Say, I have a template class with an integer parameter:
template <int N>
class A
{
public:
static int get_N()
{
return N;
}
};
template<typename T>
class B
{
public:
B()
{
cout << "N = " << T::get_N() << endl; // Accessing N via the auxiliary method
}
};
To reference the N template parameter in class B I had to create an auxiliary method in A. I would like to do something like this:
template <int N>
class A
{
};
template<typename T>
class B
{
public:
B()
{
cout << "N = " << T::N << endl; // Accessing N directly
}
};
The problem is that I'm going to have a lot of A template specializations and I don't really want to copy this auxiliary method to all of specialized classes and i don't want to introduce inheritance for this.
Is it possible to achieve what I want?
You could deduce the value from a specialization:
#include <iostream>
template <typename T> struct get_N;
template <template <int N> class T, int N>
struct get_N<T<N>> {
static constexpr int value = N;
};
template <int N> struct A {};
template <typename T>
struct B {
void f() { std::cout << get_N<T>::value << '\n'; }
};
int main() {
B<A<10>>().f();
}
You can extract N like this:
template<typename A>
struct get_N;
template<int N>
struct get_N<A<N> > : std::integral_constant<int,N> { };
This way you don't need to define anything within each A specialization, yet you can say e.g.
using X = A<3>;
cout << "N = " << get_N<X>() << endl; // prints: N = 3
However, I might still prefer to let A derive a lightweight template class that only defines a static constrexpr variable as in juanchopanza's answer. Then each A specialization would look like
template<>
struct A<3> : A_base<3> { ... };
which is not too bad. In fact, looking at both options again, I see that A_base is nothing more than
template<int N>
using A_base = std::integral_constant<int,N>;
so it could be given a more generic short name. I usually call it num.