Questions tagged [template-meta-programming]

Template meta-programming is a meta-programming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled.

template-meta-programming
253 questions with no upvoted or accepted answers
Filter by
Sorted by
Tagged with
13 votes
1 answer
709 views

Handle variadic templates for general-case mixed types and non-types

So I'm trying to make a type trait that says whether two "outer" class types are the same. ie. std::vector<int> is the same as std::vector<double>, I don't care about any inner arguments ...
Elliott's user avatar
  • 2,473
9 votes
0 answers
380 views

Linker complains about undefined references while compiling with Clang

I've encountered a really weird problem with clang. When I compile my code with C++20 using gcc-11 everything is fine. The problem appears when I try to compile it with C++20 and clang-14 (using clang-...
bielu000's user avatar
  • 2,089
8 votes
1 answer
194 views

Why does GCC allow a deduced return type in this function template when MSVC and Clang don't?

Code sample: class A { static constexpr auto GetInt() noexcept { return 6; } template<int N> std::enable_if_t< N >= GetInt(), int> func() { return N; } }; https://godbolt....
Tharwen's user avatar
  • 3,077
7 votes
0 answers
138 views

Why don't types with invalid inheritance get SFINAE-out with void_t?

Suppose we have a current class: template<typename T> struct Inheriter : public T {}; Note that its instantiation would be well-formed only if T is a class/struct that is not declared as final. ...
i cant's user avatar
  • 421
7 votes
0 answers
148 views

Reliably check for whether a class template has been instantiated, with C++11?

It used to be possible, using some C++ compilers, to check whether a templated type has already been instantiated, so that the following program syntax compiles without error: template <typename T&...
einpoklum's user avatar
  • 124k
7 votes
2 answers
861 views

Detecting a constexpr size() member function in C++ 14

I have some generic code that would like to know when it has been passed a sequence of objects the number of which is known at compile time, as then it can choose an alternative algorithmic strategy. ...
Niall Douglas's user avatar
6 votes
1 answer
452 views

The full story about the decltype + comma trick

The title should clarify what my confusion is about. I'd like to use this question to get a comprehensive answer which helps me understand how the comma operator works with decltype within SFINAE ...
Enlico's user avatar
  • 25.5k
6 votes
0 answers
111 views

Partial specialization with parameter pack behaves differently than manually expanded one

I'm trying to understand why I'm getting different behavior with 2 templates that should be equivalent to me Given template<template<typename...> class TT, typename T1, typename T2> ...
Makers_F's user avatar
  • 3,063
6 votes
0 answers
242 views

What is preventing this constexpr to be evaluated at compile time?

Considering the following code: #include <unordered_set> #include <type_traits> #include <cstring> constexpr auto cstring_hash(const char* istring) -> size_t { return (*...
Viktor Sehr's user avatar
5 votes
0 answers
276 views

How to avoid unnecessary instantiations with Boost.MP11

I have been using my own TMP library for quite some time. However, I want to start using Boost.MP11. The interface is quite nice, and, to give myself some motivation to learn it, I did the 2022 ...
Jody Hagins's user avatar
  • 28.1k
5 votes
0 answers
148 views

Is the decltype of this immediately-invoked lambda expression in C++20 well-formed?

While trying to create a toy DSL, I managed to come across an odd construct that neither clang nor gcc handled the way I expected: #include <utility> template <class...> struct ...
Patrick Roberts's user avatar
5 votes
0 answers
584 views

Dynamically build typelist in C++

I am looking for a way to dynamically build a type list at compile time. I am creating components holding different types and under the hood I'd like to build a type list that holds all the types ...
moka's user avatar
  • 4,395
5 votes
0 answers
276 views

Get lowest shared base class type in template

Let's say I have a function that takes two different templated arguments: template<typename T, typename U> void fun(T t, U u); Types T and U are part of the same inheritance tree. I'd like to ...
IanPudney's user avatar
  • 5,961
5 votes
1 answer
1k views

Getting all base classes [Meta-Programming]

Yesterday faced with problem how to get all base classes from some class. For example: class Object { public: Object() = default; }; class DerivedOne : public Object { public: DerivedOne() ...
Denis Kotov's user avatar
4 votes
0 answers
97 views

Is there a way to metaprogram long lists of extern template declarations?

I have a template struct with a non-type parameter, each instantiation of it takes a long time to compile. I know realistically I will only need to instantiate it for a few dozen or so different ...
John Robinson's user avatar
4 votes
0 answers
332 views

Compile time object list

Is there any way to create a compile time list of all those compenents? They are known at compile time so I guess it is possible. In the ideal case I would like to achieve unrolled loop, equivalent of ...
kozera2137's user avatar
4 votes
0 answers
300 views

Optimized struct serialization with template meta programming

I want to serialize a struct on a 32bit aligned platform (armv7). The idea is to serialize the struct members (which I extract with some meta programming) into a std::byte array an then to copy into a ...
Reza's user avatar
  • 360
4 votes
0 answers
241 views

How to measure static test coverage?

So, DLang (effectively) comes with code coverage built in. That's cool. My issue is, I do a lot of metaprogramming. I tend to test my templates, by static asserts: template CompileTimeFoo(size_t i) { ...
Filip Malczak's user avatar
4 votes
2 answers
233 views

SFINAE on template instantiation error?

What I'm asking is probably impossible, but I'll ask just to be sure. As previously asked and answered in this question: SFINAE and decltype(auto), functions with an auto return type may not SFINAE, ...
Alexander Kondratskiy's user avatar
3 votes
0 answers
64 views

Failed to instantiate specialized template class dispatched from constraints

As a follow up from a previous question: Giving an arbitrary container, deduce a container type of a related type, where @marek-r suggested to create template specializations like: template<...
Ranoiaetep's user avatar
  • 6,376
3 votes
0 answers
76 views

Strong aliases for types similar to mp-units "downcasting facility" using only C++14

The mp-units library has a function they call the "downcasting facility" documented here This allows long template specializations to be given short aliases which can be automatically ...
KitsuneSan's user avatar
3 votes
1 answer
146 views

how to make a c++ compile time calculation progamme recursion level deeper?

I have a programme that calculates all the prime numbers below N at compile time. For example, if I set N = 20, I'll get {2, 3, 5, 7, 11, 13, 17, 19}, if N = 10, I'll get {2, 3, 5, 7} I've tried N = ...
Badboy Lin's user avatar
3 votes
0 answers
128 views

Works fine in Visual Studio, fails to compile on G++ 9.2

The following code compiles fine with the latest version of Visual Studio Comumnity 16.5.4 configured to use the latest version of the C++ standard however it fails to compile on G++ 9.2 with a very ...
João Pires's user avatar
3 votes
0 answers
113 views

SFINAE-friendly test for object deletability

I'm interested in programmatically determining whether a delete-expression is valid for some given object. It seems like one should be able to do this using SFINAE. The code I have come up with ...
mkobierski's user avatar
3 votes
0 answers
6k views

How to generate C code from Python?

I am writing an embedded algorithm. Currently I have lookup tables that are hard-coded: static const int32_t sine[65536] = { ... } The algorithm should be portable on different platforms but, ...
nowox's user avatar
  • 27.5k
3 votes
0 answers
84 views

Using type alias with templates circular dependency

The commented line would not work, because MyArray needs MyValue but MyValue needs MyArray (this is a simplified sample). I could use a struct but I feel like there probably is a better way. ...
kiwixz's user avatar
  • 1,388
3 votes
0 answers
169 views

How to implement public iterator in C++

I have class hash_table look like this: template <typename Key, typename Value, typename Alloc> class hash_table { public: using key_type = Key; using mapped_type = Value; using ...
Phạm Văn Thông's user avatar
3 votes
0 answers
259 views

Determine conversion factors of strings describing units

In one of my project I need to determine the conversion factors of fairly complex units. I was able to write a static conversion function in case of statically defined units using the excellent boost ...
Aleph0's user avatar
  • 5,942
3 votes
1 answer
118 views

Compile error with variadic templates and overloaded << operator

I'm trying to create a class that would store a tuple of vectors. I have a strange compilation error whose origin I don't understand. The code: #include <iostream> #include <tuple> #...
Martin Vymazal's user avatar
3 votes
0 answers
543 views

Detecting instance method constexpr with SFINAE

Let me first start off by noting the very similar question here: Detecting constexpr with SFINAE. The difference is that in this question, the detection method works to detect a static method of a ...
Nir Friedman's user avatar
  • 17.4k
3 votes
1 answer
127 views

C++: tag/trait template: ensure tag is bound only once

The title is probably too vague, I'll explain what I mean. I am developing a helper library for working with TLV encoded values. In the library, each value holds a tag id, tag type code and tag ...
Vlad.Z's user avatar
  • 160
3 votes
1 answer
202 views

multidimensional std::intializer_list where the number of dimensions is specified as a template argument of its class

I have a multidimensional array which currently does not accept initializer_list initialization, but I want to allow that. However, it seems I can't specify an arbitrary number of nesting for std::...
Zach Saw's user avatar
  • 4,328
2 votes
1 answer
50 views

Type trait that gets the list of inner struct types of a given struct

Consider the following code: #include <tuple> #include <type_traits> struct foo { struct a {}; struct b {}; struct c {}; }; // we use here an hypothetical type trait '...
edrezen's user avatar
  • 503
2 votes
0 answers
120 views

How different would be these two compile-time Factorial functions in C++20

Following This link, I came up to this question. I'm trying to understand how different would be the targeting the following two compile-time functions by a C++20 compiler. consteval int Factorial(int ...
Iman Abdollahzadeh's user avatar
2 votes
1 answer
107 views

generate a unique and permanently assigned identifier (number) for .cpp files in a project

At out company we are using an error-handler in our embedded software, written in C. It is called with a preprocessor macro: #define CALL_ERROR_HANDLER(ERROR) call_error_handler(ERROR,ERROR_FILE_ID,...
Klaus's user avatar
  • 21
2 votes
2 answers
115 views

C++ Safe Recursive Dereference

I would like an elegant way to safely read data in a field which is wrapped in "nullable types" such as std::optional and std::shared_ptr. Take as example: #include <iostream> #include ...
Wilhem Meignan's user avatar
2 votes
1 answer
289 views

Compile-time publisher/subscriber pattern in C++?

In C++ we can use templates to flexibly implement the publisher/subscriber pattern. Question: Assuming that I know all publisher/subscriber relations at compile time and there are no unsubscriptions (...
vohir's user avatar
  • 21
2 votes
0 answers
53 views

SFINAE-ing on a nullary lambda expression calling a non-templated function on a template argument's instance causes compiler error

While experimenting on this, I've hit what seems to be a bug in GCC. Here's the code triggering it #include <type_traits> constexpr auto f = [](int){}; template<typename T> auto ...
Enlico's user avatar
  • 25.5k
2 votes
1 answer
65 views

Is there any way to "capture" local scope template variables (akin to a lisp special) and use as default?

In the following code: #include <iostream> #include <type_traits> // this code below won't compile unless at this point there is already // a typename rate // using rate = std::...
MB.'s user avatar
  • 1,350
2 votes
0 answers
186 views

Extending expression templates for automatic differentiation

I am trying to understand expression templates to be able to efficiently evaluate multivariate polynomials like: double PAx,PAy, aAB; double val = (PAx*PAx*PAx*PAx + 6*PAx*PAX*aAB + 3*aAB*aAB)*(PAy*...
user3116936's user avatar
2 votes
0 answers
164 views

Type trait to determine a data member's access specifier from a pointer-to-member to that member

I'm looking for a type trait that will allow me to find out if a pointer-to-member points to a public data member or not. Example : template<auto ptr> struct is_public_member_ptr { // ...
François Andrieux's user avatar
2 votes
0 answers
86 views

Can two same locally-instanced templates cross DLL boundaries?

I saw that compiler warns when dll-exposed class contains STL containers as their member or function argument, since STL is not guaranteed to generate same binaries over various compilers. However, if ...
kang-sw's user avatar
  • 23
2 votes
0 answers
66 views

Can Hana's mechanism for customizing behavior via tag-dispatching be seen as a form of adapter pattern?

tl;dr Is the customization of boost::hana::transform for std::vector (via specializing boost::hana::tranform_impl for the tag ext::std::vector) a form of Adaptor pattern that wraps the STL's std::...
Enlico's user avatar
  • 25.5k
2 votes
0 answers
81 views

How to inspect the type of argument that function A will call passed in function B with in C++ 14

I have the following code. #include <utility> #include <iostream> #include <vector> int main () { // A function that when passed another // function will call it with a ...
bradgonesurfing's user avatar
2 votes
0 answers
70 views

Recursive template class and specialized base case are causing MSVC error C1001 (works fine on GCC and Clang)

I would like to know why the following is rejected by MSVC and not Clang or GCC. I adapted the code from a post I read about a while ago and was playing around with it. There is no wider context, this ...
rad's user avatar
  • 21
2 votes
0 answers
40 views

How to safely write a store that when updated never calls the copy constructor of the stored value?

I have the problem in some generic code that I require an accumulator or more precisely a mutable variable to hold a temporary in a loop. The code is part of a Reduce implementation. I got too clever ...
bradgonesurfing's user avatar
2 votes
0 answers
146 views

How to inspect if a GENERIC lambda is callable with a certain input arguement type?

Is there anyway to check if a generic lambda is callable with a specific type?! #include <iostream> #include <type_traits> struct A { void DoAStuff() {} }; struct B { void DoBStuff() {} };...
apramc's user avatar
  • 1,356
2 votes
2 answers
56 views

Is there any pattern equivalent to virtual template function?

I'm working on a monitoring tool and I'm focusing on having low runtime overhead and a simple API. For low-overhead runtime on/off switching I chose to use the state pattern, and to simplify the usage ...
VincentDM's user avatar
  • 479
2 votes
1 answer
47 views

Modelling a symmetric relation of types like (std::plus,std::minus) with templates possible?

Is it possible to define (unordered) pairs of types in c++(20) in a way that allows to find such a pair by providing any of its members at compile time? This is trivial to achieve by either manually ...
Amr Memdu's user avatar
2 votes
1 answer
220 views

C++ Counting types without using stateful metaprogramming

I'm trying to incrementally create a list of types by registering the types with a macro. To do so I want to use a trick I found into an answer to another question. The reduced code is the following: ...
barsdeveloper's user avatar

1
2 3 4 5 6