EzDevInfo.com

Templates

Just the flat HTML/CSS templates to help you get started

How can I add reflection to a C++ application?

I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?


Source: (StackOverflow)

Can lambda functions be templated?

In C++11, is there a way to template a lambda function? Or is it inherently too specific to be templated?

I understand that I can define a classic templated class/functor instead, but the question is more like: does the language allow templating lambda functions?


Source: (StackOverflow)

Advertisements

How to Debug Variables in Smarty like in PHP var_dump()

I have some variables inside a template and I don't know where I assigned them. I need to know what is inside a particular variable; for instance, say I have a variable in smarty called member. I tried with {debug} but it didn't work, and no popup was shown.

How can I output/debug smarty variables using something like var_dump() inside the templates?


Source: (StackOverflow)

Can a member function template be virtual?

I have heard that member function templates can't be virtual. Is this true?

If they can be virtual, what is an example of a scenario in which one would use such a function?


Source: (StackOverflow)

How to emulate C array initialization "int arr[] = { e1, e2, e3, ... }" behaviour with std::array?

(Note: This question is about not having to specify the number of elements and still allow nested types to be directly initialized.)
This question discusses the uses left for a C array like int arr[20];. On his answer, @James Kanze shows one of the last strongholds of C arrays, it's unique initialization characteristics:

int arr[] = { 1, 3, 3, 7, 0, 4, 2, 0, 3, 1, 4, 1, 5, 9 };

We don't have to specify the number of elements, hooray! Now iterate over it with the C++11 functions std::begin and std::end from <iterator> (or your own variants) and you never need to even think of its size.

Now, are there any (possibly TMP) ways to achieve the same with std::array? Use of macros allowed to make it look nicer. :)

??? std_array = { "here", "be", "elements" };

Edit: Intermediate version, compiled from various answers, looks like this:

#include <array>
#include <utility>

template<class T, class... Tail, class Elem = typename std::decay<T>::type>
std::array<Elem,1+sizeof...(Tail)> make_array(T&& head, Tail&&... values)
{
  return { std::forward<T>(head), std::forward<Tail>(values)... };
}

// in code
auto std_array = make_array(1,2,3,4,5);

And employs all kind of cool C++11 stuff:

  • Variadic Templates
  • sizeof...
  • rvalue references
  • perfect forwarding
  • std::array, of course
  • uniform initialization
  • omitting the return type with uniform initialization
  • type inference (auto)

And an example can be found here.

However, as @Johannes points out in the comment on @Xaade's answer, you can't initialize nested types with such a function. Example:

struct A{ int a; int b; };

// C syntax
A arr[] = { {1,2}, {3,4} };
// using std::array
??? std_array = { {1,2}, {3,4} };

Also, the number of initializers is limited to the number of function and template arguments supported by the implementation.


Source: (StackOverflow)

std::function vs template

Thanks to C++11 we received the std::function family of functor wrappers. Unfortunately, I keep hearing only bad things about these new additions. The most popular is that they are horribly slow. I tested it and they truly suck in comparison with templates.

#include <iostream>
#include <functional>
#include <string>
#include <chrono>

template <typename F>
float calc1(F f) { return -1.0f * f(3.3f) + 666.0f; }

float calc2(std::function<float(float)> f) { return -1.0f * f(3.3f) + 666.0f; }

int main() {
    using namespace std::chrono;

    const auto tp1 = system_clock::now();
    for (int i = 0; i < 1e8; ++i) {
        calc1([](float arg){ return arg * 0.5f; });
    }
    const auto tp2 = high_resolution_clock::now();

    const auto d = duration_cast<milliseconds>(tp2 - tp1);  
    std::cout << d.count() << std::endl;
    return 0;
}

111 ms vs 1241 ms. I assume this is because templates can be nicely inlined, while functions cover the internals via virtual calls.

Obviously templates have their issues as I see them:

  • they have to be provided as headers which is not something you might not wish to do when releasing your library as a closed code,
  • they may make the compilation time much longer unless extern template-like policy is introduced,
  • there is no (at least known to me) clean way of representing requirements (concepts, anyone?) of a template, bar a comment describing what kind of functor is expected.

Can I thus assume that functions can be used as de facto standard of passing functors, and in places where high performance is expected templates should be used?


Edit:

My compiler is the Visual Studio 2012 without CTP.


Source: (StackOverflow)

What ReSharper 4+ live templates for C# do you use? [closed]

What ReSharper 4.0 templates for C# do you use?

Let's share these in the following format:


[Title]

Optional description

Shortcut: shortcut
Available in: [AvailabilitySetting]

// Resharper template code snippet
// comes here

Macros properties (if present):

  • Macro1 - Value - EditableOccurence
  • Macro2 - Value - EditableOccurence



Source: (StackOverflow)

In Rails, how do you render JSON using a view?

Suppose you're in your users controller and you want to get a json response for a show request, it'd be nice if you could create a file in your views/users/ dir, named show.json and after your users#show action is completed, it renders the file.

Currently you need to do something along the lines of:

def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json{
      render :json => @user.to_json
    }
  end
end

But it would be nice if you could just create a show.json file which automatically gets rendered like so:

def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json
  end
end

This would save me tons of grief, and would wash away that horribly dirty feeling I get when I render my json in the controller


Source: (StackOverflow)

How to concatenate strings in django templates?

I want to concatenate string in django template tag like

{% extend shop/shop_name/base.html %}

Here shop_name is my variable and I want to concatenate this with rest of path.
Suppose I have shop_name=example.com

And I want result to extend shop/example.com/base.html


Source: (StackOverflow)

Function passed as template argument

I'm looking for the rules involving passing C++ templates functions as arguments.

This is supported by C++ as shown by an example here:

#include <iostream>

void add1(int &v)
{
  v+=1;
}

void add2(int &v)
{
  v+=2;
}

template <void (*T)(int &)>
void doOperation()
{
  int temp=0;
  T(temp);
  std::cout << "Result is " << temp << std::endl;
}

int main()
{
  doOperation<add1>();
  doOperation<add2>();
}

Learning about this technique is difficult, however. Googling for "function as a template argument" doesn't lead to much. And the classic C++ Templates The Complete Guide surprisingly also doesn't discuss it (at least not from my search).

The questions I have are whether this is valid C++ (or just some widely supported extension).

Also, is there a way to allow a functor with the same signature to be used interchangeably with explicit functions during this kind of template invocation?

The following does not work in the above program, at least in Visual C++, because the syntax is obviously wrong. It'd be nice to be able to switch out a function for a functor and vice versa, similar to the way you can pass a function pointer or functor to the std::sort algorithm if you want to define a custom comparison operation.

   struct add3 {
      void operator() (int &v) {v+=3;}
   };
...

    doOperation<add3>();

Pointers to a web link or two, or a page in the C++ Templates book would be appreciated!


Source: (StackOverflow)

What are some uses of template template parameters in C++?

I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?


Source: (StackOverflow)

Get Visual Studio to run a T4 Template on every build

How do I get a T4 template to generate its output on every build? As it is now, it only regenerates it when I make a change to the template.

I have found other questions similar to this:

http://stackoverflow.com/questions/1293320/t4-transformation-and-build-order-in-visual-studio (unanswered)

http://stackoverflow.com/questions/405560/how-to-get-t4-files-to-build-in-visual-studio (answers are not detailed enough [while still being plenty complicated] and don't even make total sense)

There has got to be a simpler way to do this!


Source: (StackOverflow)

C++ difference of keywords 'typename' and 'class' in templates

For templates I have seen both declarations:

template < typename T >

And:

template < class T >

What's the difference?

And what exactly do those keywords mean in the following example (taken from the German Wikipedia article about templates)?

template < template < typename, typename > class Container, typename Type >
class Example
{
     Container< Type, std::allocator < Type > > baz;
};

Source: (StackOverflow)

Default template arguments for function templates

Why are default template arguments only allowed on class templates? Why can't we define a default type in a member function template? For example:

struct mycclass {
  template<class T=int>
  void mymember(T* vec) {
    // ...
  }
};

Instead, C++ forces that default template arguments are only allowed on a class template.


Source: (StackOverflow)

Why is the C++ STL is so heavily based on templates? (and not on *interfaces*)

I mean, aside from its obligating name (the Standard Template Library)...

C++ initially intended to present OOP concepts into C. That is: you could tell what a specific entity could and couldn't do (regardless of how it does it) based on its class and class hierarchy. Some compositions of abilities are more difficult to describe in this manner due to the problematics of multiple inheritance, and the fact that C++ supports the concept of interfaces in a somewhat clumsy way (compared to java, etc), but it's there (and could be improved).

And then templates came into play, along with the STL. The STL seemed to take the classical OOP concepts and flush them down the drain, using templates instead.

There should be a distinction between cases when templates are used to generalize types where the types themeselves are irrelevant for the operation of the template (containers, for examples). Having a vector makes perfect sense.

However, in many other cases (iterators and algorithms), templated types are supposed to follow a "concept" (Input Iterator, Forward Iterator, etc...) where the actual details of the concept are defined entirely by the implementation of the template function/class, and not by the class of the type used with the template, which is a somewhat anti-usage of OOP.

For example, you can tell the function:

void MyFunc(ForwardIterator<...> *I);

Update: As it was unclear in the original question, ForwardIterator is ok to be templated itself to allow any ForwardIterator type. The contrary is having ForwardIterator as a concept.

expects a Forward Iterator only by looking at its definition, where you'd need either to look at the implementation or the documentation for:

template <typename Type> void MyFunc(Type *I);

Two claims I can make in favor of using templates: compiled code can be made more efficient, by tailor-compiling the template for each used type, instead of using vtables. And the fact that templates can be used with native types.

However, I am looking for a more profound reason why abandoning classical OOP in favor of templating for the STL? (Assuming you read that far :P)


Source: (StackOverflow)