This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 8 years ago.
I'm trying to learn templates in c++ and i came across with a doubt that i can't find answers for. I'm sorry in advance if this is not a proper question.
If i have the following code:
template< class T >
T func( T a, T b )
{
return a + b;
}
And then:
int number = func( 2, 3 );
Will number simply be set to 5 or will a function
int func( int a, int b )
{
return a + b;
}
be generated?
I need to know if i can make a template that checks if a certain string is in a file.
Both (: The code:
int number = func( 2, 3 );
will instantiate the template function for int type, but compiler may (depending on compiler options) actually optimize it to just:
int number = 5;
A function equivalent to
int func( int a, int b )
{
return a + b;
}
will certainly be generated (unless, of course, it's optimized out). To see this, try
int (*func_int)(int, int) = func<int>; // pointer to instantiated function
int number = func_int(2, 3); // sets number to 5
Related
This question already has answers here:
How to create an object in a form like this: ifstream in();
(1 answer)
Trying to understand default constructors and member initialisatioon
(3 answers)
What is the purpose of the Most Vexing Parse?
(6 answers)
Is most vexing parse a formally defined concept
(2 answers)
Closed 3 months ago.
I have this concept and template function
template<typename T>
concept Averageable = std::is_default_constructible<T>::value &&
requires(T a, T b)
{
{ a += b } -> std::convertible_to<T>;
{a / size_t(1)} -> std::convertible_to<T>;
};
template<typename T>
requires Averageable<T>
T mean(const T* vals, size_t size)
{
T sum();
for (size_t i{}; i < size; size++)
{
sum += vals[i];
}
return sum / size;
}
And for some reason calling like this
const int a[]{1,2,3};
const int res = mean<int>(a, 3);
results in the following IntelliSense error
no instance of function template matches the argument list argument types are: (size_t, int)
I'm using Visual Studio 2022 with c++ 20. I have tried searching for a reason why this is happening endlessly (as well as a proper tutorial for concepts) and have come up short.
I'm new to using concepts/requires so if anyone has any insight as to why this doesn't work or how to properly do it I would greatly appreciate it
Your concept/require is fine. The problem you got here is actually most vexing parse. Namely this line:
T sum();
Despite it might look like you are constructing an integer, it's actually declaring a function that returns a T.
To fix it, simply change the parentheses to braces:
T sum{};
Sidenote, in the for loop, you probably wanted i++ instead of size++.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I know that this is allowed in C, but I am used not to update the value of a variable passed by value.
In my "coding style", a parameter passed by value is not changed.
I mean that I prefer this:
void func(int var)
{
int locVar = var;
if(something)
{
locVar = locVar/2;
}
// [some stuff using locVar]
}
over this:
void func(int var)
{
if(something)
{
var = var/2;
}
// [some stuff using var]
}
I assume that the compiler will not produce different assembly if the register optimizations are enabled, but still, is there any good reason to prefer one of the two code snippets?
is there any good reason to prefer one of the two code snippets?
1) Compilers are not created equal. int locVar = var; may create faster code. (I was surprise to find this true in a given application.) This is local or micro-optimization and is only useful in select cases and of course may result is different performance when compiled with other options or on another machine.
2) Less is better. Introducing a synonym as in int locVar = var;is more code and more variables to understand and maintain. Usually this is less helpful.
3) Both code snippets generate valid code. So this is a style issue too. If your coding group has a coding guideline concerning this, better to follow that than be different for trivial reasons.
Select reasons to prefer one over the other: Yes. Strong reasons: In general no. When in doubt of which way to go, the easy to maintain one wins outs (IMO).
No.
From a computers point of view - no difference. Optimization will do the job.
From a personal point of view - a matter of taste
From a meta-view - do not set up pitfalls
Very often initial parameter values are needed multiple times in a function, the more common style therefore is not to overwrite parameters. It is very convenient to have the values available for debugging, logging messages (“wrote n bytes”), in catch clauses and so on. As this is more or less common style, a maintainer could easily miss your itsy-bitsy-premature-optimization. Such optimizations were common in the age of non-optimizing C compilers, nowadays they are just 'because-I-can' stuff. Remember, we write code to be readable by humans. Compilers can do that anyway.
In general the more variables are introduced the less readable and more complicated the code will be.
Sometimes it is even difficult to invent two names for one entity that semantically they would look identically.
For example a function listing can occupy several screens. In this case if you encountered a name like locVar you need to scroll the function listing backward to determine what this name means.
Moreover a function can have several parameters. Are you going to introduce new aliases for each parameter?
For readers of your code it will not be clear that you introduced new local variables just to support your coding style. They for example can think that you changed the function and forgot to remove variables that are not necessary any more.:)
Consider for example a recursive function that calculates the sum of digits of a number.
unsigned int sum( unsigned int x )
{
const unsigned int Base = 10;
unsigned int digit = x % Base;
return digit + ( ( x /= Base ) == 0 ? 0 : sum( x ) );
^^^^^^^^^^^^^
}
or that can be written like
unsigned int sum( unsigned int x )
{
const unsigned int Base = 10;
return x % Base + ( x / Base == 0 ? 0 : sum( x / Base ) );
}
What is the purpose to introduce a new local variable as an alias of x in this function?
unsigned int sum( unsigned int x )
{
const unsigned int Base = 10;
unsigned int y = x;
unsigned int digit = y % Base;
return digit + ( ( y /= Base ) == 0 ? 0 : sum( y ) );
}
As for me then the first function implementation without the intermediate variable y is more clear. The recursive nature of the function is more visible when the same variable x is used.
If you want to point out that a parameter is not changed in a function you can declare or define the function with the parameter that has qualifier const.
For example
unsigned int sum( const unsigned int x )
{
const unsigned int Base = 10;
return x % Base + ( x / Base == 0 ? 0 : sum( x / Base ) );
}
In C++ function calls could look like
#include <iostream>
constexpr unsigned int sum( const unsigned int x )
{
const unsigned int Base = 10;
return x % Base + ( x / Base == 0 ? 0 : sum( x / Base ) );
}
int main()
{
std::cout << sum( 123456789 ) << std::endl;
int a[sum( 123456789 )];
std::cout << sizeof( a ) << std::endl;
}
The program output is
45
180
This question already has answers here:
what does this mean char (*(*a[4])())[5]?
(4 answers)
Closed 6 years ago.
so I've been studying pointers, trying to understand them.
I know that in the following line
int f(int ni, int n);
f is a function that accepts two int variables as its input and it returns an int as the result
If I write the following line
int (*f)(int ni, int n);
then f is a function pointer
However, what happens when I write something like?
int (*f[4])(int p);
Thanks for your help.
This is an array of 4 pointers to function, example:
int foo(int p) {
return 0;
}
int (*f[4])(int p);
f[0] = foo;
f[1] = foo;
f[2] = foo;
f[3] = foo;
refer to this link :
Array functions pointer
There's explainations about what is does and how to implement it
This question already has answers here:
sizeof operator returns different values for c & c++?
(2 answers)
Closed 7 years ago.
I just came across this simple code snippet and am wondering why output of this program when it's compiled by a C compiler is 4 and when it's compiled by a C++ one is 8.
#include <stdio.h>
int x;
int main(){
struct x {int a; int b;};
printf("%d", sizeof(x));
return 0;
}
C++ output is rational (8 = 4 + 4 = sizeof(x.a) + sizeof(x.b)), but output of C isn't. So, how does sizeof work in C?
C : https://ideone.com/zj5Qd2
C++ : https://ideone.com/ZZ4v6S
Seems C prefers global variables over local ones. Is it right?
In C, a struct definition like struct x { int a; int b; }; does not define a type x, it defines a type struct x. So if you remove the int x; global, you'll find the C version does not compile.
This question already has answers here:
Can we overload operators for built-in types like int or float?
(3 answers)
Closed 7 years ago.
I would like to re-define
+
operator.
So, I make a simple code like below code.
int operator+(const int &a, const int &b)
{
int temp = a-b;
return temp;
}
int main()
{
int a = 10;
int b = 5;
cout << a+b << endl;
}
I can re-define with Class type... But I don't want to use Class.
How can I resolve this issue?
You cannot define the operators for plain old data types like int.
You could build your own int class (my_int, say) and include the line #define int my_int. But this would be extremely pernicious and wouldn't work with compile-time evaluated literal expressions.
You cannot redefine operator for int (or any other built in type).
If you say, what do you want to do, we might find some solution.