Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
FAT32 SHAMER
Aug 16, 2012



I have to write a function template max_generic() that takes as input an array of either int, float, or double, and returns the maximum element in the array. My professor's ppt slides are less than clear on this, and so far everything I've found on the internet is way over my head. I know how to find the max value of an array, but I don't know how to make it so that it can take multiple types. Going by what I read, I guess if you go

C++ code:
#include "Template.h"
#include <iostream>
using namespace std;

template <typename T>

void print+max( const T array, int count )
{
    for(int i=0; i < count; i++)
    {
        if( array[i]>temp )
        {
            temp = array[i];
        }
    }
    cout << "The maximum value of the array is: " << temp << endl;
    return 0;
    
}
then take user input from the main class and pass it to the array that should populate the array? Should I make the user input from type auto or should I make user input of type T like the array is of type T?

Adbot
ADBOT LOVES YOU

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Tusen Takk posted:

I have to write a function template max_generic() that takes as input an array of either int, float, or double, and returns the maximum element in the array. My professor's ppt slides are less than clear on this, and so far everything I've found on the internet is way over my head. I know how to find the max value of an array, but I don't know how to make it so that it can take multiple types. Going by what I read, I guess if you go

C++ code:

#include "Template.h"
#include &lt;iostream&gt;
using namespace std;

template &lt;typename T&gt;

void print+max( const T array, int count )
{
    for(int i=0; i &lt; count; i++)
    {
        if( array[i]&gt;temp )
        {
            temp = array[i];
        }
    }
    cout &lt;&lt; "The maximum value of the array is: " &lt;&lt; temp &lt;&lt; endl;
    return 0;
    
}

then take user input from the main class and pass it to the array that should populate the array? Should I make the user input from type auto or should I make user input of type T like the array is of type T?

You want to

- declare and initialize temp (be careful how you choose the initial value; imagine an array with all negative values)
- make const T[] array

and then it looks like it should work.

xgalaxy
Jan 27, 2004
i write code
Also it doesn't have to be named T. You can put any valid identifier there you want. I found it helpful to do that when I was first learning templates.

FAT32 SHAMER
Aug 16, 2012



Subjunctive posted:

You want to

- declare and initialize temp (be careful how you choose the initial value; imagine an array with all negative values)
- make const T[] array

and then it looks like it should work.
Is there a reason why you replaced < and > with < and >?

xgalaxy posted:

Also it doesn't have to be named T. You can put any valid identifier there you want. I found it helpful to do that when I was first learning templates.

Yeah we've always used T in Java, and I saw it being used on other example code so I just went with it :v:

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Tusen Takk posted:

Is there a reason why you replaced &lt; and &gt; with &lt and &gt?

No, it's a bug in the latest Awful.app. Sorry!

FAT32 SHAMER
Aug 16, 2012



Subjunctive posted:

No, it's a bug in the latest Awful.app. Sorry!

I thought that may be an XML/PHP thing, no worries!

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Illusive gently caress Man posted:

I'm a little confused on 'recv()' and how it behaves. Let's say the following happens

My server accepts a connection from a client and begins polling the client's socket with select()
The client sends "whattup homeslice?" or something of similar length.
On the server, select() indicates there is new data on a socket. The server calls recv(client_fd, buf, 2048, 0)

What situations will cause recv to return less than the length of the message the client sent?

I'm not a networking expert, but IIRC it depends on the kind of socket. Specifically, on a SOCK_STREAM, a bunch of bytes sent in one write/send can get broken up across multiple reads/receives for a multitude of reasons; for example, TCP implementations often combine multiple writes into one packet that can end up larger than your buffer, and the internet is permitted to basically arbitrarily split TCP packets. A SOCK_DGRAM is different, and you should never get a partial recv as long as the buffer is large enough for the protocol's maximum message size; UDP's maximum message size is actually 65507 bytes, although of course your application-layer protocol can promise to never send a message that large, and the chance of random packet loss goes up with larger packets.

SSL is a stream protocol and AFAIK makes no guarantees about messages being received completely. Among other things, the need to encrypt payloads makes it more likely that messages won't fit into tidy packet sizes.

FAT32 SHAMER
Aug 16, 2012



It doesn't seem to like my code at all

C++ code:
#include "Template.h"
#include <iostream>

using namespace std;

template < typename T >

void printMax( const T[] array, int count ) //Expected ')'
{
    int temp = 0;
    
    for( int i=0; i < count; i++ ) //Reference to overloaded function could not be resolved; did you mean to call it?
    {
        if( array[i] > temp ) //Type name requires a specifier or qualifier; Variable declaration in condition must have an initialiser; expected ')';
        {
            temp = array[i];
        }
    }
    cout << "The maximum value of the array is: " << temp << endl;
    
}

int main()
{
    int count, number;
    const T[] array = 0; //Expected ';' at end of declaration; C++ requires a type specifier for all declarations; definition of variable with array type needs an explicit size or initializer;
    
    cout << "Please enter the number of items you wish to put into the array";
    cin >> number;
    
    for( int i = 0; i < number; i++ )
    {
        T arrayMember = 0;
        
        cout << "Please enter an int, float, or double: ";
        cin >> arrayMember; //use rof undeclared identifier 'arrayMember'
        arrayMember -> array[]; //expected expression; use of undeclared identifier 'arrayMember'
        count++;
    }
    
    printMax( array[i], count ); //cannot refer to class template 'array' without a template argument list; expected expression
    
    return 0;
}
Going by the amount of errors I can see that there's something I'm just not getting. Why isn't typename T working in the main method? Why is it saying that arrayMember is undeclared?

Two more weeks and I'm done with this lovely class :smithicide:

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
The parser is getting super confused because that's not how you declare arrays. Do const T array[].

Also you have no idea how arrays work in C; you need to be using something like a vector if the class allows it.

Also I have no idea what language that thing you're doing with -> is even supposed to be from, but it ain't C++.

FAT32 SHAMER
Aug 16, 2012



rjmccall posted:

The parser is getting super confused because that's not how you declare arrays. Do const T array[].

Also you have no idea how arrays work in C; you need to be using something like a vector if the class allows it.

Also I have no idea what language that thing you're doing with -> is even supposed to be from, but it ain't C++.

I wanted to use a vector but the professor wants an array, and the professor has ppt slides that say you can use -> to insert things into arrays. I have no idea why I thought taking this class would be a good idea, honestly :saddowns:

edit: gently caress it i'm switching to vectors

Star War Sex Parrot
Oct 2, 2003

I love C++.

FamDav
Mar 29, 2008

Tusen Takk posted:

the professor has ppt slides that say you can use -> to insert things into arrays.

i cant even with this. its like the hypest thing

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Tusen Takk posted:

I wanted to use a vector but the professor wants an array, and the professor has ppt slides that say you can use -> to insert things into arrays. I have no idea why I thought taking this class would be a good idea, honestly :saddowns:

edit: gently caress it i'm switching to vectors

Are you sure that -> thing isn't just pseudocode?

Sorry about the array-decl error, got distracted by a bug I introduced into Awful that the [] tripped, and stopped paying attention. :downs:

FAT32 SHAMER
Aug 16, 2012



Subjunctive posted:

Are you sure that -> thing isn't just pseudocode?

Sorry about the array-decl error, got distracted by a bug I introduced into Awful that the [] tripped, and stopped paying attention. :downs:

Heh, it may be. and no worries :shobon:

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
I mean, you can use a normal array if you're allowed to make assumptions about the maximum number of elements will go in it, and that's probably what your professor wants you to do, because professors are all about teaching terrible style in the process of introducing basic language concepts. It's very C-ish, but you can do it. You just need to declare something like T array[100];, then assign each value you read into the next element of the array. There will be extra elements of the array that you don't use, but that's not a problem — it's a minor performance problem if T ends up being some complex type like std::string.

Star War Sex Parrot
Oct 2, 2003

rjmccall posted:

Also I have no idea what language that thing you're doing with -> is even supposed to be from, but it ain't C++.

Subjunctive posted:

Are you sure that -> thing isn't just pseudocode?
Seeing all of this -> discussion mixed with his array hopelessness made me curious if you can actually use it with pointer arithmetic to dereference an array of object's members. I never really use pointer arithmetic with arrays anyway, but -> seems to work.
C++ code:
#include <iostream>

class Butt
{
public:
	int x;
	void Foo() const
	{
		std::cout << x << " butts" << std::endl;
	}
};

int main()
{
	Butt test[5] {6,7,8,9,10};

	(test+2)->Foo();

    return 0;
}
which outputs 8 butts.
Also that probably confused Tusen Takk even more.

Star War Sex Parrot fucked around with this message at 02:51 on Apr 15, 2014

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Sure. You could even do it without arithmetic and act directly on the first element. It's just... so unlikely of a thing to do intentionally that there probably ought to be a warning for it, but there isn't because it's too unlikely to even come up as a mistake.

hooah
Feb 6, 2006
WTF?
I'm having trouble with a priority queue. I have one of Vertex, and the comparator is
C++ code:
struct greater{
	bool operator()(const Vertex* l, const Vertex* r){
		return l->getTotalPathWeight() > r->getTotalPathWeight();
	}
};
I'm working on a Dijkstra's algorithm between two given vertices. I found that vertices could get updated and mess up the order of the priority queue. I noticed that it re-sorted itself on .pop(), so I wrote the last three lines to force that to happen. However, I'm getting an "invalid heap" error while debugging after I process the first two vertices in the priority queue. Why would this be happening?

Here's my traversal function:
C++ code:
void Graph::traverse(int from, int to){
	for (auto &i : _vertices){
		if (i.second.getId() != from){
			i.second.setTotalPathWeight(DBL_MAX);
			_travList.push(&(i.second));
		}
	}
	_vertices[from].setTotalPathWeight(0);
	_travList.push(&(_vertices.find(from)->second));

	while (!_travList.empty()){
		auto v = _travList.top();
		_travList.pop();
		if (v->getId() == to)
			break;
		for (auto &i : v->_adjacent){
			double newPath = v->getTotalPathWeight() + i.second;
			if (newPath < _vertices[i.first].getTotalPathWeight()){
				_vertices[i.first].setTotalPathWeight(newPath);
				_vertices[i.first].setPrevious(v->getId());
			}
		}
		// Force the priority queue to re-heapify
		auto dummy = _travList.top();
		_travList.pop();
		_travList.push(dummy);
	}
}
And here's the input adjacency list (vertex label, neighbor's label, path weight from vertex to neighbor):
code:
0 1 5.0 
0 2 10.0 
1 3 3.0 
1 4 6.0 
3 2 2.0 
3 4 2.0 
3 5 2.0 
4 6 6.0 
5 6 2.0 
7 9 1.0 
8 7 2.0 
8 9 4.0

FamDav
Mar 29, 2008
also tusen you can obviate the dependency on array vs vector by using iterators and iterator_traits

code:
#include <iostream>                                                                                                                                                                                                 
#include <iterator>                                                             
                                                                                
template<typename T>                                                            
typename std::iterator_traits<T>::value_type                                    
maximum(T begin, T end)                                                         
{                                                                               
   T max = begin;                                                               
                                                                                
   for (; begin != end; ++begin)                                                
   {                                                                            
      max = *max < *begin ? begin : max;                                        
   }                                                                            
                                                                                
   return *max;                                                                 
}                                                                               
                                                                                
int main()                                                                      
{                                                                               
   int myarray[] = {1,2,3,4,5,6,5,4,3,2,1};                                     
   std::cout << maximum(myarray,myarray+11) << std::endl;                       
}   

FAT32 SHAMER
Aug 16, 2012



Star War Sex Parrot posted:

Seeing all of this -> discussion mixed with his array hopelessness made me curious if you can actually use it with pointer arithmetic to dereference an array of object's members. I never really use pointer arithmetic with arrays anyway, but -> seems to work.
C++ code:
#include <iostream>

class Butt
{
public:
	int x;
	void Foo() const
	{
		std::cout << x << " butts" << std::endl;
	}
};

int main()
{
	Butt test[5] {6,7,8,9,10};

	(test+2)->Foo();

    return 0;
}
which outputs 8 butts.

Also that probably confused Tusen Takk even more.

It did :argh:

FamDav posted:

also tusen you can obviate the dependency on array vs vector by using iterators and iterator_traits

code:
#include <iostream>                                                                                                                                                                                                 
#include <iterator>                                                             
                                                                                
template<typename T>                                                            
typename std::iterator_traits<T>::value_type                                    
maximum(T begin, T end)                                                         
{                                                                               
   T max = begin;                                                               
                                                                                
   for (; begin != end; ++begin)                                                
   {                                                                            
      max = *max < *begin ? begin : max;                                        
   }                                                                            
                                                                                
   return *max;                                                                 
}                                                                               
                                                                                
int main()                                                                      
{                                                                               
   int myarray[] = {1,2,3,4,5,6,5,4,3,2,1};                                     
   std::cout << maximum(myarray,myarray+11) << std::endl;                       
}   

That helps, I think. Ah well I somehow got 90's and 100's on all my previous projects so low score on this is something I can accept worst case scenario :v:

WHERE MY HAT IS AT
Jan 7, 2011

Basically, when you have an array in C++, it allocates an area in memory of (size of array type) * (number of array elements). The variable name for your array is actually just a pointer to the first element in that array, so you can use pointer arithmetic to move around in the array. The (test+2) line is equivalent to &test[2] (although it would appear that isn't actually a legal statement), and you can then dereference that pointer and call the method. I can't see when you would ever need to use that particular method to access an array of objects, but there you have it.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Tusen Takk posted:

It doesn't seem to like my code at all
I think nobody's mentioned yet that the big problem your code has is that type T is only valid inside your template function printMax (the double line-break between the template<> and the function declaration is pretty confusing, those things generally go on the same line if they fit, or adjacent lines otherwise, they certainly belong together).

There is no type T in main, you're supposed to be using whatever type you want (make an int array probably), then the template function is designed to figure out what the input type is, substitute it for T, and thus compile a function that will worth with it.

FAT32 SHAMER
Aug 16, 2012



roomforthetuna posted:

I think nobody's mentioned yet that the big problem your code has is that type T is only valid inside your template function printMax (the double line-break between the template<> and the function declaration is pretty confusing, those things generally go on the same line if they fit, or adjacent lines otherwise, they certainly belong together).

There is no type T in main, you're supposed to be using whatever type you want (make an int array probably), then the template function is designed to figure out what the input type is, substitute it for T, and thus compile a function that will worth with it.

I actually just figured this out, it works, and now I will hopefully never bother you guys again because that was the last lab of the semester. Thanks to everyone for being incredibly patient with me and my terrible, awful, horrible C++ warcrime code and I promise I will [hopefully] never use C++ professionally (or under any circumstances whatsoever, actually).

FamDav
Mar 29, 2008

Tusen Takk posted:

I actually just figured this out, it works, and now I will hopefully never bother you guys again because that was the last lab of the semester. Thanks to everyone for being incredibly patient with me and my terrible, awful, horrible C++ warcrime code and I promise I will [hopefully] never use C++ professionally (or under any circumstances whatsoever, actually).

thats the wrong attitude. just because you've had to deal with a weird professors weird requirements doesnt mean c++ is a bad thing.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

FamDav posted:

thats the wrong attitude. just because you've had to deal with a weird professors weird requirements doesnt mean c++ is a bad thing.

Yeah, C++ is a bad thing for many other reasons, not just a weird professor

FAT32 SHAMER
Aug 16, 2012



Suspicious Dish posted:

Yeah, C++ is a bad thing for many other reasons, not just a weird professor

Basically this. Coming from Java, it was an especially curvy curveball thrown at me and I'm honestly glad that I'm done with it.

Star War Sex Parrot
Oct 2, 2003

Tusen Takk posted:

Basically this. Coming from Java, it was an especially curvy curveball thrown at me and I'm honestly glad that I'm done with it.
Learn C# :getin:

FAT32 SHAMER
Aug 16, 2012




I'm taking Python next semester and I was considering C# as well. I've heard it's basically the best parts of Java and C++, c/d?

Star War Sex Parrot
Oct 2, 2003

Tusen Takk posted:

I've heard it's basically the best parts of Java and C++, c/d?
Ehhhh it depends on what you consider the "best parts" of each respective language. If you consider the portability of Java and the performance of C++ to be their best parts, then no C# is not just a perfect language that marries both of those. If you consider Java's garbage collection and Visual Studio for C++ to be their best parts, well then maybe you'd have an argument.

Either way, yes C# is related to both Java and C++ in some ways and I find it to be a very nice language and the .NET Library to be well put together and all have their places in the world. We now return you to C++ chat. :)

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Thanks, Star Wars Sex Parrot. Next up on C++ chat: class template friend class template member templates, and are they right for your children?

FamDav
Mar 29, 2008

rjmccall posted:

Thanks, Star Wars Sex Parrot. Next up on C++ chat: class template friend class template member templates, and are they right for your children?

some children.

better children.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

rjmccall posted:

Thanks, Star Wars Sex Parrot. Next up on C++ chat: class template friend class template member templates, and are they right for your children?
On the subject of templates full of templates, the most annoying (C++11) error message is the one that goes something like "you're not allowed to specialize your function template inside the template class definition". gently caress you compiler, you know what I wanted, you could totally figure out how to do it, and some fucker just put an arbitrary rule there that you won't do it so I have to type my insane outer-template-class declaration a bunch of extra times? It's not even like you're encouraging me to separate my declaration and definition between header files and cpp files because this poo poo still involves templates so it's necessarily going in a header file.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

rjmccall posted:

Thanks, Star Wars Sex Parrot. Next up on C++ chat: class template friend class template member templates, and are they right for your children?

No. Next?

Vanadium
Jan 8, 2005

Next up Desperately trying to edge into C++ chat for the past three years: Rust

Zopotantor
Feb 24, 2013

...und ist er drin dann lassen wir ihn niemals wieder raus...
Want to have your mind completely blown?

This is legal syntax in C/C++:
code:
int fart(int butt[])
{
    return 2[butt];
}

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"
If you're using C++11, you can even check your bounds at compile time so you don't have those pesky out-of-bounds access issues.
C++ code:
template<size_t n>
int fart(int (&butt)[n])
{
    static_assert(n and n-1 &~ 1, "poop");
    return 2[butt];
}
And don't forget the overload for array rvalues (and by extension, temporaries (yes, these are possible if you really want them))
C++ code:
template<size_t n> int fart(int (&&butt)[n]);

Scrapez
Feb 27, 2004

If anyone can point me in the right direction on this I'd appreciate it. I'm learning C and having a problem removing duplicates from a char array.

My code works fine for reading two .txt files content into a char array and my function works for sorting it in alphabetical order. The problem is with removing duplicates from the list. Thank you in advance for any direction.

Here is what I have:

code:
#include <stdio.h>
#include <string.h>

#define NUMSTR 10
#define STRLNG 9

void funcsort(char [ ][STRLNG]);

FILE *inptr, *inpts, *outptt;

int main()
{
	char listunsorted[20][STRLNG], listsorted[20][STRLNG];
	inptr = fopen("list1.txt", "r");
	inpts = fopen("list2.txt", "r");
	int i, j, k, num=20;
	
	//Code reading list1.txt into listunsorted character array
	for (i = 0; i < NUMSTR; i++)
	{
		fscanf(inptr, "%8s", listunsorted[i]);
	}
	
	fclose(inptr);

	//Code reading list2.txt into listunsorted character array
	for (i = 0; i < NUMSTR; i++)
	{
		fscanf(inpts, "%8s", listunsorted[i+NUMSTR]);
	}
	
	fclose(inpts);
	
	//Code to print the list as it was read from the two files
		for (i = 0; i < 20; i++)
	{
		printf("%s\n", listunsorted[i]);
	}
	
	printf("Below should be the sorted unique list:\n\n");
	
	//Code to Alphabetize listunsorted
	funcsort(listunsorted);
	
	//Code to remove duplicates from listunsorted
	for (i = 0; i < num; i++)
	{
		for (j = (i + 1); j < num;)
		{
			if(strcmp(listunsorted[i], listunsorted[j]) == 0)
			{
				for (k = j; k < num; k++)
				{
					strcpy(listunsorted[k], listunsorted[k+1]);
					num--;
				}
			}
			else
				j++;
		}
	}
	
	//Code to print the sorted list without duplicates
	for (i = 0; i < 20; i++)
	{
		printf("%s\n", listunsorted[i]);
	}

	return 0;	
}

void funcsort( char listunsorted[ ][STRLNG])
{
	int i, j;
	char tempname[STRLNG];
	
	for (i = 0; i < 20 - 1; i++)
	{
		for(j = i + 1; j < 20; j++)
		{
			if(strcmp(listunsorted[i], listunsorted[j]) > 0)
			{
				strcpy(tempname , listunsorted[i]);
				strcpy(listunsorted[i] , listunsorted[j]);
				strcpy(listunsorted[j] , tempname);
			}
		}
	}
	
	return;
}

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!

Tusen Takk posted:

I've heard it's basically the best parts of Java and C++, c/d?
C# is basically just "Java done right," and by "done right" I mean not spending 5-years implementing features that everyone's been asking for or refusing to implement them at all.

roomforthetuna posted:

On the subject of templates full of templates, the most annoying (C++11) error message is the one that goes something like "you're not allowed to specialize your function template inside the template class definition". gently caress you compiler, you know what I wanted, you could totally figure out how to do it, and some fucker just put an arbitrary rule there that you won't do it so I have to type my insane outer-template-class declaration a bunch of extra times? It's not even like you're encouraging me to separate my declaration and definition between header files and cpp files because this poo poo still involves templates so it's necessarily going in a header file.
I'm more annoyed by template function partial specialization not being possible, and I'm still not sure why it isn't.

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

Scrapez posted:

If anyone can point me in the right direction on this I'd appreciate it. I'm learning C and having a problem removing duplicates from a char array.

My code works fine for reading two .txt files content into a char array and my function works for sorting it in alphabetical order. The problem is with removing duplicates from the list. Thank you in advance for any direction.

Your algorithm for removing duplicates from a sorted list is O(n3), which tells me it's probably wrong. It looks like you're trying to find the duplicates and then shift everything left, but even that should only be two loops deep. It turns out, this can be done in a single pass with some insight.

The key is to keep track of the last unique element in your list. Initially, you can only assume the first string is unique. Then, you look at every other string, from second to last, and do one of two things:
  • If it's the same as your first element, do nothing.
  • If it's different, you found a unique string (thanks to the list being sorted and all). Copy it to after the "last" unique string, and that's your new last unique string.
After you've gone through the entire list this way, the number of unique elements is one more than the index of the last unique string.

Here's the above in C. Maybe reconsider the whole listunsorted name, considering you never actually use listsorted. It was a bit awkward writing this, considering it depends on listunsorted being sorted.

C code:
int last_unique = 0;
for (i = 1; i < num; i++)
{
	if (strcmp(listunsorted[last_unique], listunsorted[i]) != 0)
	{
		last_unique++;
		strcpy(listunsorted[last_unique], listunsorted[i]);
	}
}
num = last_unique + 1;

Adbot
ADBOT LOVES YOU

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

OneEightHundred posted:

I'm more annoyed by template function partial specialization not being possible, and I'm still not sure why it isn't.

I'm not sure what you mean by not possible. Templated functions can be partially specialized. For example:

C++ code:
#include <iostream>
using namespace std;

template<typename T> void foo(T) {
    cout << "unspecialized\n";
}

template<> void foo<int>(int) {
    cout << "specialized\n";
}

void foo(int) {
    cout << "overloaded\n";
}

int main() {
    foo('c');
    foo(10);
    foo<int>(10);
}
It has the following output:
code:
unspecialized
overloaded
specialized
Without the second overload of foo (i.e. the only one that's not a template), the output becomes:
code:
unspecialized
specialized
specialized
Just beware that their behavior in overload resolution gets a bit funky. As always with C++, there are ways to ensure that template overloads behave the way you want, but it can get ugly.

My personal pet peeve is the lack of literal operator templates for user-defined-char- and user-defined-string-literals. Maybe I belong in the coding horrors thread, but I want to be able to build data structures at compile-time from a string using template metaprogramming. For example, compile-time format strings with portable type-safety:
C++ code:
template<char... Cs> auto operator""_f();

int main() {
    // calls `operator""_f<'H', 'e', ... , '\n'>()`
    // which returns `formatter<std::string, int>` or similar
    auto fmt = "Hello, %s! %d\n"_f;
    std::cout << fmt % "world" % 5;
}
But alas, only user-defined-integer- and user-defined-floating-literals get the fancy templates.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply