dimanche 25 janvier 2015

String Argument vs. Template Parameter for Formatting

I'm wondering if one of these two methods for supplying a format string could be considered "more correct". Obviously both work, but one requires a series of constant strings to be maintained in a namespace, while the other uses a class:



#include <ctime>
#include <iostream>

// Method 1: constant strings:
char const* STANDARD = "%c";
char const* ISO8601 = "%Y-%m-%dT%H:%M:%S%z";

const std::string timestamp(char const* format) {
time_t raw_time;
time(&raw_time);
struct tm* time_info = localtime(&raw_time);
const size_t maxsize = 80;
char time_str[maxsize];
strftime(time_str, maxsize, format, time_info);
return time_str;
}

// Method 2: Class-based formatter used as a template parameter:
struct standard {
static inline char const* format() { return "%c"; }
};

struct iso8601 {
static inline char const* format() { return "%Y-%m-%dT%H:%M:%S%z"; }
};

// The formatter is supplied as a template parameter.
template<typename T>
const std::string timestamp() {
time_t raw_time;
time(&raw_time);
struct tm* time_info = localtime(&raw_time);
const size_t maxsize = 80;
char time_str[maxsize];
strftime(time_str, maxsize, T::format(), time_info);
return time_str;
}

int main() {
// Method 1: constant strings:
std::cout << timestamp(ISO8601) << std::endl;

// Method 2: template:
std::cout << timestamp<iso8601>() << std::endl;
}


Thoughts? Suggestion? I'm not as familiar with template programming (traits, strategies, etc.) as I could be, so I'm really curious is one of these is "better" or "more correct" than the other.


Aucun commentaire:

Enregistrer un commentaire