C++ template explicit instantiation - c++

I have working code like this.
#include <iostream>
struct A{
template<typename T>
void foo(T val);
};
template<typename T> void A::foo(T val)
{
std::cout << val << std::endl;
}
// link template "against" int
template void A::foo(int val);
// #include header here
int main(){
A a;
a.foo(12);
}
Template is in separate CPP file, but linking works, because of explicit instantiation:
template void A::foo(int val);
Then I did some re-factoring, and code looks like this:
#include <iostream>
template<typename G>
struct A{
template<typename T>
void foo(T val);
};
template<typename G>
template<typename T> void A<G>::foo(T val)
{
std::cout << val << std::endl;
}
// link template "against" int - not working
//template<typename G>
//template void A<G>::foo(int val);
int main(){
A<float> a;
a.foo(12);
}
How can I "link" T=int, but keep G "unknown"?

It is called explicit instantiation.
You can't do this, because G is unknown and it is not a single type. It is rather a set of types.

You can not do this. To actually produce a code from a template (I guess that's what you call link), the compiler need to know all the template parameters.
So you are left with the standard options for template instantiation: either explicitly tell the compiler what T and G will be used, either let the compiler see full code for the template member wherever you use it (that is, include the code in header).

TL;DR you can't.
In your case I'd just specify the type you intend to use
template void A<float>::foo(int val);
or (rather bulky) explicitly instantiate all the types G could be used for.
There is no way you can explicitly instantiate the template if G cannot be deduced.
Notice that linking works not because this syntax is a linker command but because your compiler is producing code that is later found at link-time. See more here

Related

How can I use a nested type belonging to a templated class in another template function in C++?

I'm setting up a function that initializes tuples based on a tuple type and a functor struct For that has a size_t template argument INDEX to retain the compile-time index. This functor may also depend on other template arguments T.... Because of this the functors exist within other structures (TClass in this example) that hold these template arguments.
The initialization function (called Bar here) has a template<std::size_t> class template argument to ensure that the used class actually can store the index.
While the design I've come up with works fine when I call it from a non-template function, it does not compile if the template T2 of a function does determine the template parameter of the wrapper TClass.
Here is the definition of the functor For wrapped inside TClass:
#include <cstdlib>
template <typename T> struct TClass {
template<std::size_t INDEX> struct For {
void operator()() {}
};
};
And here are the function calls i want to use:
template <template<std::size_t> class FOR> void bar() {
//...
}
template <typename T> void foo() {
bar<TClass<T>::For>(); //Does not compile
}
int main() {
bar<TClass<int>::For>(); //Works
foo<int>();
return 0;
}
The compiler output for the faulty foo-call is:
error: dependent-name ‘TClass<T>::For’ is parsed as a non-type, but instantiation yields a type
Bar<TClass<T>::For>(); //Does not compile
I know that dependent type names usually have to be preceded by a typename but this is also not necessary for the first bar-call. I assumed it was because the template argument can only be interpreted as a type. So I thought that maybe typename would result in correct compilation but if I change foo to
template <typename T> void foo() {
bar<typename TClass<T>::For>(); //Does not compile
}
I get:
error: ‘typename TClass<int>::For’ names ‘template<long unsigned int INDEX> struct TClass<int>::For’, which is not a type
Bar<typename TClass<T>::For>(); //Does not compile
I've also come up with a design where the ()-operator of TClass depends on the template INDEX which also works fine because it is not necessary to use nested types anymore. It looks like this:
#include <cstdlib>
template <typename T> struct TClass {
template<std::size_t INDEX> void operator()() {}
};
template <typename FOR> void bar() {
//...
}
template <typename T> void foo() {
bar<TClass<T>>(); //Does compile
}
Apparently it is not possible to use dependent type names in functions where the template of the type is determined by the function's template parameters, but why? And how do I implement this correctly? To make writing future type checks with type traits easier I would prefer it if I can use a functor.
The compiler cannot know that TClass<T>::For refers to a template at the first stage of template instantiation. It needs a bit of help with template keyword. Fix:
template <typename T> void foo() {
bar<TClass<T>::template For>();
}

Why do we need 'template <class T>' before implementing all templated class methods

If we have a standard class:
class Foo {
public:
int fooVar = 10;
int getFooVar();
}
The implementation for getFooVar() would be:
int Foo::getFooVar() {
return fooVar;
}
But in a templated class:
template <class T>
class Bar {
public:
int barVar = 10;
int getBarVar();
}
The implementation for getBarVar() must be:
template <class T>
int Bar<T>::getBarVar(){
return barVar();
}
Why must we have the template <class T> line before the function implementation of getBarVar and Bar<T>:: (as opposed to just Bar::), considering the fact that the function doesn't use any templated variables?
You need it because Bar is not a class, it's a template. Bar<T> is the class.
Bar itself is a template, as the other answers said.
But let's now assume that you don't need it, after all, you specified this, and I added another template argument:
template<typename T1, typename T2>
class Bar
{
void something();
};
Why:
template<typename T1, typename T2>
void Bar<T1, T2>::something(){}
And not:
void Bar::something(){}
What would happen if you wanted to specialize your implementation for one type T1, but not the other one? You would need to add that information. And that's where this template declaration comes into play and why you also need it for the general implementation (IMHO).
template<typename T>
void Bar<T, int>::something(){}
When you instantiate the class, the compiler checks if implementations are there. But at the time you write the code, the final type (i.e. the instantiated type) is not known.
Hence the compiler instantiates the definitions for you, and if the compiler should instantiate something it needs to be templated.
Any answer to this question boils down to "because the standard says so". However, instead of reciting standardese, let's examine what else is forbidden (because the errors help us understand what the language expects). The "single template" case is exhausted pretty quickly, so let's consider the following:
template<class T>
class A
{
template<class X>
void foo(X);
};
Maybe we can use a single template argument for both?
template<class U>
void A<U>::foo(U u)
{
return;
}
error: out-of-line definition of 'foo' does not match any declaration in 'A<T>'
No, we cannot. Well, maybe like this?
template<class U>
void A<U>::foo<U>(U u)
{
return;
}
error: cannot specialize a member of an unspecialized template
No. And this?
template<class U, class V>
void A<U>::foo(V u)
{
return;
}
error: too many template parameters in template redeclaration
How about using a default to emulate the matching?
template<class U>
template<class V = U>
void A<U>::foo(V u)
{
return;
}
error: cannot add a default template argument to the definition of a member of a class template
Clearly, the compiler is worried about matching the declaration. That's because the compiler doesn't match template definitions to specific calls (as one might be used to from a functional language) but to the template declaration. (Code so far here).
So on a basic level, the answer is "because the template definition must match the template declaration". This still leaves open the question "why can we not just omit the class template parameters then?" (as far as I can tell no ambiguity for the template can exist so repeating the template parameters does not help) though...
Consider a function template declaration
tempalte <typename T>
void foo();
now a definition
void foo() { std::cout << "Hello World"; }
is either a specialization of the above template or an overload. You have to pick either of the two. For example
#include <iostream>
template <typename T>
void foo();
void foo() { std::cout << "overload\n"; }
template <typename T>
void foo() { std::cout << "specialization\n"; }
int main() {
foo();
foo<int>();
}
Prints:
overload
specialization
The short answer to your question is: Thats how the rules are, though if you could ommit the template <typename T> from a definition of the template, a different way would be required to define an overload.

extern template does not work for gcc?

C++11 introduced a feature called 'extern template' which indicates that template instance exists in other translate unit.(Am I right?)
This(http://www.youtube.com/watch?v=3annCCTx35o) lecture also tells that if you specify extern template and don't include instantiation, the linker will produce error.(around 2:25 in the video)
So, I've tried to build next code:
#include <iostream>
template<class T>
struct Foo
{
static constexpr int type_size = sizeof(T);
};
extern template struct Foo<int>;
int main()
{
std::cout<< Foo<int>::type_size << std::endl;
return 0;
}
I expected the build will fail because this file does not contain explicit instantiation nor specialization, but gcc just builds it up the result runs well.
What am I missing? Or, am I misunderstanding something? Or, does not gcc support extern template well?
Update
I've tried a class with non-inline function, and extern template works as expected!
#include <iostream>
template<class T>
struct Foo
{
static void print(T t);
};
template<class T>
void Foo<T>::print(T t) { std::cout << t << std::endl; }
extern template struct Foo<int>;
// template struct Foo<int>;
int main()
{
Foo<int>::print(1);
return 0;
}
Above source is not built without the commented line.
Thank you all guys!
if you specify extern template and don't include instantiation, the linker will produce error.
No, not necessarily. There is only a problem if you actually use the template. You're using a compile-time constant defined as a static member of that template, but that is replaced by the constant's value at compile-time. And after that replacement, there is no longer any use of the template, so there is no need for a definition of the template.

Automatic Template Specialization in Template Function Argument

I came up with the following problem (code below):
template<class T>
void printname(const T& t){std::cout<<t<<std::endl;}
template<class T>
void applyfunc(const T& t, void (*f)(const T& )){(*f)(t);}
int main(){
const int a=1;
applyfunc(a,printname);
getchar();
return 0;
}
My problem is that it compiles with vc++8(VS2005), and GCC, CLang (on Ubuntu 12.04)
but fails to compile with vc++ 2008 express.
It seems to be legal code but I don't really get why.
If anyone could explain it I'd appreciate it.
Supposing it is legal, is there any way that something similar could be done with functors?
I assume you meant to use func for printname (or vice versa).
For what it's worth, I believe this code to be legal, and the fact that VS2008 (and also VS2010; I don't have VS2012 handy at the moment) rejects it looks like a compiler bug.
Re: something similar with functors - see if this does it for you:
#include <iostream>
struct printname {
template<class T>
void operator()(const T& t) { std::cout<<t<<std::endl; }
};
template<class T, class F>
void applyfunc(const T& t, F f) { f(t); }
int main(){
const int a=1;
applyfunc(a, printname());
return 0;
}
I am not sure as of whether the question is why it works in most compilers or why it fails in VS2008. If the question is the former, we can discuss a simplified version of this:
template <typename T>
void f(T const &) {}
void g(void (*fn)(std::string const&) {}
g(f); // compiles
void (*fn)(double const &) = f;
Pointers to functions are a bit special in the language, since the same name can refer to different overloads. When the name of a function is used in code, the compiler cannot determine which of the overloads is determined by itself, so it will use the target of the expression to determine this. In the case of g(f), since the g function takes a function of type void (std::string const&), it will resolve f to mean f<std::string>, while in the case of the initialization of fn the compiler will resolve to the specialization f<double>.
Note that this is a very commonly used feature of the language:
std::cout << std::endl;
The name std::endl refers to a template:
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
The compiler sees that this is being called on the object std::cout, of type basic_ostream<char,char_traits<char>>, and that the only specialization that matches the call to operator<< is that where charT == char and traits == char_traits<char> and picks the correct specialization.
On Visual Studio 2010, the solution is easy yet subtle. You simply need to add <int> after printname in the line applyfunc(a,printname<int>);. The compiler needs help figuring out the template type to use.
#include <iostream>
struct printname
{
template<class T>
void operator()(const T& t)
{
std::cout << t << std::endl;
}
};
template<class T, class F>
void applyfunc(const T& t, F f)
{
f(t);
}
int main()
{
const int a=1;
applyfunc(a, printname<int>); // Add <int> here
return 0;
}

Can I exclude some methods from manual template instantiation?

We have complex template classes that have some methods which will not work with certain policies or types. Therefore, when we detect those types (at compile time, using type-traits) we fire a static assertion with a nice message.
Now we do a lot of manual template instantiation as well. Partly it is so that the methods are forced to compiler to syntax check the methods. It also reduces compile time for the library user. The problem is that the static assertions are always fired and consequently we cannot manually instantiate the template class in question.
Is there a workaround for this?
EDIT: To make it clearer, here is an example (the explicit instantiation in this case will fail on someFunc1():
// header
template <typename T>
class someClass
{
void someFunc() {}
void someFunc1() { static_assert(false, assertion_failed); }
};
// source
template someClass<int>; // Explicit instantiation
EDIT2: Here is another example. This time you can compile it to see what I mean. First compile right away. The code should compile. Then Uncomment [2] and the static assertion should fire. Now comment out [2] and Uncomment [1]. The static assertion will fire because you are explicitly instantiating the template. I want to avoid removing explicit instantiation because of the benefits that come with it (see above for benefits).
namespace Loki
{
template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
}
#define LOKI_STATIC_CHECK(expr, msg) \
{ Loki::CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }
template <typename T>
class foo
{
public:
void func() {}
void func1() { LOKI_STATIC_CHECK(sizeof(T) == 4, Assertion_error); }
};
template foo<int>;
//template foo<double>; // [1]
int main()
{
foo<int> a;
a.func1();
foo<double> b;
//b.func1(); //[2]
return 0;
}
You can't have both: you can't have a static assertion to prevent instantiation and explicitly instantiate the type! This is an obvious contradiction. What you can have, however, is conditionally included functionality even though it is somewhat a pain in the neck: If a certain member function is not supposed to be supported for certain types, you can move this function into a base class which conditionally has it. This way you wouldn't use a static assertion but just remove the member function. I realize that this introduces interesting other problems, e.g. with respect to the location of member variables, but I think in the context you are describing this is the best you can get.
Here is a quick example of how this could look like:
template <typename T, bool = std::numeric_limits<T>::is_integer> struct foo_base;
template <typename T> struct foo_base<T, false> { /* intentionally left blank */ };
template <typename T> struct foo_base<T, true> { void foo() { /*...*/ } };
template <typename T>
struct Foo: foo_base<T> { /* .... */ };
template struct Foo<int>; // will have foo()
template struct Foo<double>; // will not have foo()
Alright, so if you're forcing the instantiation of all methods using explicit instantiation, you can't get away with any compile time tricks to prevent instantiation of the offending methods, such as enable_if. It'd be easy enough to move the error to runtime, but that's undesirable.
I think the best you can do is move the error to link time, which will statically ensure that the program does not contain a code path that could potentially call the prohibited function, but the error messages won't be very helpful to anyone that doesn't know about the restriction you're imposing. Anyway, the solution is to declare a specialization of the prohibited member functions but not define them:
template<typename T>
struct Foo {
void bar() {
std::cout << "bar\n";
}
void baz() {
std:: cout << "baz\n";
}
};
template<> void Foo<int>::baz(); // use of Foo<int>::baz() will resolve to this specialization, and linking will fail
template struct Foo<int>;
template struct Foo<char>;
int main() {
Foo<int> f;
f.bar();
// f.baz(); // uncommenting this line results in an ugly link time error
Foo<char> b;
b.bar();
b.baz(); // works with Foo<char>
}
The static asserts no longer help give nice error messages when a mistake is made in client code, but you might want to leave them in because they'll fire if you forget to provide a specialization.
enable_if is a flexible mechanism for precise template methods targeting, may be what you are after. Example:
#include <string>
#include <iostream>
#include <boost/utility.hpp>
#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>
template <class T> class mywrapper
{
T _value;
template <class V>
typename boost::enable_if<boost::is_scalar<V>, void>::type printval_(V const& value)
{
BOOST_STATIC_ASSERT(boost::is_scalar<V>::value);
std::cout << "scalar: " << value << std::endl;
}
template <class V>
typename boost::enable_if<boost::is_compound<V>, void>::type printval_(V const& value)
{
BOOST_STATIC_ASSERT(boost::is_compound<V>::value);
std::cout << "compound: " << value << std::endl;
}
public:
mywrapper(T const& value):_value(value) { }
void printval() { printval_(_value); }
};
template class mywrapper<int>;
template class mywrapper<std::string>;
int main()
{
mywrapper<int> ival(333);
mywrapper<std::string> sval("test");
ival.printval();
sval.printval();
return 0;
}
I did not get an opportunity to test enable_if as suggested by bobah but I did come up with a solution that does not require boost and that satisfies my original requirement to a good extent (I say good and not full, will explain at the end)
The solution is to put a dummy template on the code that will fail if compiled under some selected types and is fine under others. So:
struct dummyStruct {};
#define DUMMY_TEMP typename dummy
#define DUMMY_PARAM dummyStruct
namespace Loki
{
template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
}
#define LOKI_STATIC_CHECK(expr, msg) \
{ Loki::CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }
template <typename T>
class foo
{
public:
void func() {}
template <typename T_Dummy>
void func1() { LOKI_STATIC_CHECK(sizeof(T) == 4, Assertion_error); }
};
template foo<int>;
template foo<double>; // [1]
int main()
{
foo<int> a;
a.func1<DUMMY_PARAM>();
foo<double> b;
//b.func1<DUMMY_PARAM>(); //[2] - this is a static error
return 0;
}
In all of my template code, these kind of functions (i.e. the ones that have static asserts OR work on some types and may fail on others by using type traits [in which case there is a selection of several different functions for different types]) are hidden from the client. So in my implementation, adding the extra dummy parameter is an OK compromise.
As a bonus, it lets me know that this function is designed to be used by only certain types. Furthermore, my original problem of explicit instantiation is solved by this simple technique.