Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this A<B>::c("d") construction mean? Name space with a template?

It looks like c is a function that takes "d" as argument. I know that :: is used to indicated name spaces and their sub-name spaces. But what A<B> mean? I know that B is class. I also know templates can be used for classes, functions and structures. But in this example it looks like we use a template for a name space.

like image 230
Roman Avatar asked Apr 10 '13 07:04

Roman


1 Answers

It means you have a class template called A accepting a type parameter, and you instantiate that template with type B as its type argument.

That class template, in turn, defines either (1) a static member callable object c (could be a regular function) which accepts an object of a type to which a string literal is convertible, or (2) a type alias c for a type which is constructible from a string literal (and in that case you are constructing a temporary of that type).

In both cases, you access an entity defined inside class template A by using the same scope resolution operator (::) that you would use to access an entity defined inside a namespace (after all, both classes and namespaces define a scope).

As an example of (1) (live example):

#include <iostream>

struct B { };

template<typename T>
struct A
{
    static void c(const char* s) { std::cout << s; }
};

int main()
{
    A<B>::c("d");
}

As another example of (1) using a callable object rather than a function (live example):

#include <iostream>

struct B { void operator () (const char* c) { std::cout << c;  } };

template<typename T> 
struct A
{
    static T c;
};

template<typename T>
T A<T>::c;

int main()
{
    A<B>::c("d");
}

As an example of (2) (live example):

#include <iostream>

struct B { B(const char* s) { std::cout << s; } };

template<typename T> 
struct A
{
    typedef T c;
};

int main()
{
    A<B>::c("d");
}
like image 103
Andy Prowl Avatar answered Sep 18 '22 23:09

Andy Prowl