I found interesting question and decided to examine top answer in detail.
I asked myself why there needs structure and try to rewrote the code without it:
#include <iostream>
template <int N> void out(std::ostream& os) {
out<N-1>(os);
os << N << std::endl;
}
template <> void out<1>(std::ostream& os){
os << 1 << std::endl;
}
int main(){
out<100>(std::cout);
}
And then I tried to refactor the code.
I got something like this:
#include <iostream>
template <int N> void out() {
if (N != 1) {
out<N-1>();
std::cout << N << std::endl;
}
else {
std::cout << 1 << std::endl;
}
}
int main(){
out<100>();
}
I don't understand why this code didn't work.
Any ideas?
The problem is that the if condition is evaluated at run-time. When you get to the instantiation where N = 1, it doesn't know that the first block of the if statement won't execute. It proceeds to instantiate out<0> and so on. If we had a static if, this would be possible, but it probably won't happen very soon.
Templates are expanded during compilation while if statements are only checked during run-time which is a different later stage. In your case the compiler will try to expand indefinetely as there is no specific implementation of the function for a fixed value of N(that used to be 1).
Related
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::integral_constant<int, 10>;
template<typename rate=rate> void functionA()
{
static_assert(rate::value > 5);
std::cout << "functionA: " << rate::value << std::endl;
}
template<typename rate> void loop()
{
functionA<std::integral_constant<int, 50>>(); // => prints "functionA: 50"
functionA(); // <- I would like this call to infer loop's functions's rate template type (which would be 20)
}
void other()
{
using rate = std::integral_constant<int, 12>;
functionA(); // => prints "functionA: 12"
}
void bare_loop()
{
functionA(); // should give compile time-error: no 'rate' in semantic scope
}
int main() {
loop<std::integral_constant<int, 20>>();
return 0;
}
I would like to be able to write a templated function which has a default parameter value which remains undeclared until compilation is necessary.
The above shows the most minimal piece of code to express this idea.
What I'm trying to achieve is directly inspired by Lisp's variable capture mechanism (lexical and dynamic scope).
To be clear: this is entirely a compile-time problem and solution.
Is this possible in the current state of affaires of C++?
I am really not sure if I understood what you intended, but if you want is a function that could either take the parameter rate at compile time or at runtime, well, one possibility would be to use a default parameter in function "functionA", determined by the template parameter. So you can define the default in compile time, and override it in runtime if needed.
I leave an example below in case it helps, however I can't understand what it the desired use case, and it can be possibly
a bad design:
#include <iostream>
#include <cassert>
constexpr int infer() { return 123; }
const int MIN_RATE_LIM = 5;
template<int t_rate=infer()> void functionA(const int rate = t_rate)
{
assert(rate > MIN_RATE_LIM);
std::cout << "functionA: " << rate << std::endl;
}
template<int rate> void loop()
{
for(int i = 0; i < 10; i++ )
{
functionA<50>();
functionA<rate>();
functionA<rate>(12); // <- 12 will overlap the value 10 in this line
}
}
int main() {
loop<10>();
return 0;
}
I am attempting to create a wrapper around class functions. The purpose of my wrapper is to test input, output, and enforce order of operations with various calls throughout my program. I am trying to not make any changes to the callee class. Attached is an example of what I am trying to achieve, but unable to figure out.
Main.cpp
#include "func_warpper.h"
#include "func.h"
int main()
{
func_wrapper fw
fun func;
int origValue = 5;
fw.caller([&](int origValue) { func.f(origValue); }, origValue);
int output = func.getResult().number;
std::cout << " value outputed by function 2 : " << output << std::endl;
// output
// note that above line does give me the result I am looking for
// however, I want to be able to get this inside the function of caller
return 0;
}
func.h .... I want this to be unmodified
#ifndef FUN_H
#define FUN_H
class fun
{
public:
struct result
{
int number;
};
fun();
~fun();
void f(int value);
struct result getResult(){return this->testResult;};
private:
struct result testResult;
};
#endif
func.cpp .... I want this to be unmodified
#include "func.h"
fun::fun(){
this->testResult.number = 0;
return;
}
fun::~fun(){
return;
}
void fun::f(int value){
int updateValue = value * 5;
this->testResult.number = updateValue;
}
func_wrapper.h .... I can modify this until the cows come home, please go ham with recommended changes :)
class func_wrapper
{
public:
struct new_result
{
int new_number;
};
func_wrapper();
~func_wrapper();
void caller(std::function<void(int)> clb, int val);
struct new_result getNewResult() { return this->new_testResult; };
private:
struct new_result new_testResult;
};
#endif
func_wrapper.cpp .... same as above, I can modify this until the cows come home, please go ham with recommended changes :)
#include "func_wrapper.h"
func_wrapper::func_wrapper()
{
//ctor
this->new_testResult.new_number = 0;
return;
}
func_wrapper::~func_wrapper()
{
//dtor
}
void func_wrapper::caller(std::function<void(int)> clb, int val)
{
std::cout << " value entered into function: " << val << std::endl;
// clb(val); seems to call the function but does not store locally anything
clb(val);
clb;
// clb; seems to store all the information locally however I seem unable to
// to reach the infromation: clb -> [functor] -> func -> testResult -> number
// would like ...
int output = clb ??? // the result of what gets filled from number struct
// if I attempt to #include func.h
// func func;
// func.getResult().number; locally the answer is zero with or without delay
}
Through several days of searching, I have not found anything that can help with this problem, to include similar enough questions on stack overflow. Any help would be greatly appreciated, thank you.
So, my understanding is that inside func_wrapper::caller you want to be able to access the wrapped class that is inside your callback. Unfortuately, the way you are doing it, is impossible. There is no (legitimate) way to reach inside the function and access its arguments.
However, if you break up the operation into its component parts, you can do what you want. You would want a caller function more like this:
template <typename Type, typename Function>
void caller(Type&& functor, Function function, int val)
{
std::cout << " value entered into function: " << val << std::endl;
std::invoke(function, functor, val);
std::cout << "value inside wrapper: " << functor.getResult().number << "\rn";
}
and then call it like this.
fw.caller(func, &fun::f, origValue);
https://godbolt.org/z/151YfEeoo
#JohnFilleau had mentioned to pass the class object instead of the function from within the class. The following is the solution based on example code that he provided, and I modified to work with the example. I realize the question is confusing but would like to thank both JohnFilleau and Taekahn for the discussion.
In main.cpp
int main()
{
func_wrapper fw;
fun func;
int origValue = 5;
fw.caller2(func, origValue);
return 0:
}
func_wrapper::caller2
void func_wrapper::caller2(fun& fun, int val)
{
std::cout << " value entered into function: " << val << std::endl;
fun.f(val);
int output = fun.getResult().number;
std::cout << " did this work: " << output << std::endl;
}
In the header I had to add
#include "func.h"
with the change to the header as follows
void caller2(fun& fun, int val);
The following code should be creating the in-class thread_local only once, but it ends up initializing it on every access
#include <iostream>
#include <thread>
using std::cout;
using std::endl;
template <typename T>
class Something {
public:
struct TLBookkeeping {
TLBookkeeping() {
std::cout << "TLBookkeeping() " << std::this_thread::get_id() << std::endl;
}
};
static void foo();
static thread_local TLBookkeeping bookkeeping_;
};
template <typename T>
thread_local typename Something<T>::TLBookkeeping Something<T>::bookkeeping_;
template <typename T>
void Something<T>::foo() {
std::cout << &bookkeeping_ << std::endl;
std::cout << &bookkeeping_ << std::endl;
}
namespace {
struct Struct {};
}
int main() {
Something<Struct>::foo();
}
(https://wandbox.org/permlink/fgqCDHV0axKDRt89)
Interestingly the bug only shows when Struct is in an anonymous namespace.
Does someone know if this is a clang bug (gcc does it right - https://wandbox.org/permlink/hsxRj8OdYbt4Eeck) or an inherently incorrect usage of thread_local? If the latter, what is the correct usage? If the former, what exactly is the bug? And is this documented somewhere? Should we open a bug report?
When you find that a compiler causes runtime behavior which you are relatively certain is incorrect; and another popular compiler does not cause that same behavior - that is sufficient, IMHO, in order to file a bug against said compiler.
As #SamVarshavchik suggestions, you:
Visit LLVM's bug tracker
Create an account if you don't have one
Look for duplicates (e.g. using the term "thread-local")
If you don't find one - you file a bug
I've done just that, so now we have bug 42111.
At worst - it'll be marked as a dupe.
edit: It was not a dupe, and has just now (June 5th 2019) been fixed.
I've been recently getting into template wizardry and in particular CRTP. I know that templates are used to make the compiler generate code for us so I was wondering if it were possible to make a template "decide" which parts of a function we would like it to include for a particular class. For example if I have the following code:
crtp.h
#include <iostream>
using std::endl;
using std::cout;
template<class T>
class A {
public:
void func() {
constexpr unsigned short mask = T::GetMask();
if (mask & 1) {
/*
Do Something
*/
cout << "Mask 1" << endl;
}
if (mask & 1 << 3) {
/*
Do Something else
*/
cout << "Mask 2" << endl;
}
}
};
class B : public A<B> {
friend class A<B>;
protected:
static constexpr unsigned short GetMask() { return 0x0001; }
};
class C : public A<C> {
friend class A<C>;
protected:
static constexpr unsigned short GetMask() { return 0x0009; }
};
main.cpp
#include "ctrp.h"
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
using std::getchar;
using std::endl;
int main() {
B b;
C c;
cout << "B:" << endl;
b.func();
cout << endl << "C:" << endl;
c.func();
getchar();
}
Which when executed produces:
B:
Mask 1
C:
Mask 1
Mask 2
This works great, does exactly what I want it to. The problem is from my standpoint the if statements should be unnecessary. As I am dealing with constant expressions the compiler should have everything it needs to simply skip the branching and know to execute the first part for class B and both parts for class C.
I would like to cash in on this and specifically tell the compiler to remove the sections that are unnecessary for the particular class to avoid unnecessary branching at runtime. Unfortunately I have no idea how to do this, any ideas? Thanks in advance
Edit
In response to some of the awesome suggestions C++17's constexpr if expression is a near perfect solution that I had no idea existed, but am unfortunately unable to use. I am limited to using C++14.
If you care about performance, the compiler will very likely optimize out all "dead" branches and even the if condition, if it can evaluate it during compile time.
What is worse, all the branches need to be well formed until C++17 constexpr if. In this case, you can "outsource" the functionality to special (static member) functions and use specialization to invoke the right one. See #R Sahu's answer for the example.
Emulating if/else at compile time using template metaprogramming does not work that way. You have to imagine if/else using a different mindset.
Instead of
if (mask & 1) {
/*
Do Something
*/
cout << "Mask 1" << endl;
}
if (mask & 1 << 3) {
/*
Do Something else
*/
cout << "Mask 2" << endl;
}
you'll have to use something along the lines of:
function1_selector<mask & 1>::dostuff();
function2_selector<mask & 1 << 3 >::dostuff();
where
template <bool> struct function1_selector
{
static void dostuff() { /* Do nothing */ }
};
template <> struct function1_selector<true> // Specialize for true
{
static void dostuff() { /* Do something useful */ }
};
Add code for function2_selector similarly.
The following code gives me a warning when using the Intel compiler icpc13.
#include <iostream>
template<int N>
class base
{
public:
double x[N];
};
template<int N>
class derived : public base<2*N>
{
public:
void print()
{
if (N==1)
{
std::cout << this->x[1] << std::endl;
}
else if (N==2)
{
std::cout << this->x[3] << std::endl;
}
}
};
int main(int argc, char* argv[])
{
derived<1> temp1;
derived<2> temp2;
temp1.print();
temp2.print();
}
Result: % icpc-13.1.163 main.cpp main.cpp(29): warning #175:
subscript out of range std::cout<x[3]<
during instantiation of "void derived::print() [with N=1]" at line
41
This is obviously not a danger since the if statement protects this line of code if the template argument is 1.
I know that I "should" do template specialization for such things, but there is some shared code in the real functions that make the if statements on template arguments really handy.
Question is…is this a "bad" thing to do, or is this incorrect compiler behavior? I don't get warnings with gcc, or xlc.
I chose the pragma solution. This ends up looking like this:
void print()
{
#ifdef __INTEL_COMPILER
#pragma warning push
#pragma warning disable 175
#endif
if (N==1)
{
std::cout<<this->x[1]<<std::endl;
}
else if (N==2)
{
std::cout << this->x[3] << std::endl;
}
#ifdef __INTEL_COMPILER
#pragma warning pop
#endif
}
};
From what I can tell, the push saves the warning flags before the disable, and the pop restores them.
Compilers do check code branches even they're inactive due to compile-time constants.
ICPC seems to be the only that checks the array bounds, but you could possibly run into other annoying warnings, like from Visual C++, which warns about constant conditional expressions when checking N (C4127 with warning level 4).
I definitely would take care of the warning, your mileage may vary:
disable warning with compiler option -wd175
disable warning at this specific point with vendor-dependent #pragma warning(disable: 175)
specialize the derived<>::print() method and factor out common code:
template<>
void derived<1>::print()
{
std::cout << x[1] << std::endl;
call_common();
}
template<>
void derived<2>::print()
{
std::cout << x[3] << std::endl;
call_common();
}
factor out the switch on N into its own specialized method derived<>::print_x():
template<>
void derived<1>::print_x()
{
std::cout << x[1] << std::endl;
}
template<>
void derived<2>::print_x()
{
std::cout << x[3] << std::endl;
}
template<int N>
void derived<N>::print()
{
print_x();
// ...
}