Consider the following module:
module M;
// a private, non-exporting function
int id(int x) {
return x;
}
export
template <class T>
int f(T x) {
return id(0);
}
export
int g(int y) {
return id(1);
}
And the following C++ code using it:
import M;
int main() {
g(42);
return 0;
}
It successfully compiles with VS2015 update 1 and works, but if I replace g with f, the compiler complains: error C3861: 'id': identifier not found.
How to fix it?
You face this problem because of templates instantiation rules. For the same reason as you include templates definition in C++ header files (and don't define them in separate .cpp files), you can't export template function from module in this way.
It's not a good practice to export template functions or classes from module because you should have all instantiations, that will probably be used, within this module. However if you want to implement it in this way for some reason, you should instantiate function f() with T as int in the module, e.g. add useless call with integer argument within this module.
Related
In a .cpp file I implement a bubble_sort algorithm. Inside the bubble_sort function I use swap(a, b). However I don't specify "using name space std" in this cpp file. (Actually there is no header in this .cpp file) I still could complile the program without any warning or error. I know that if I want to use some customary function in that bubble_sort function, I need to at lease declare that function in the same file. But I don't understand why I don't need to do any thing for the swap. Below is my cpp file:
bubble_sort.cpp
template <typename Type>
void bubble_sort(Type* originarray, int lengthofarray)
{
int ii=lengthofarray-1;
while(ii>0)
{
for (int jj=0;jj<ii;jj++)
{
if (originarray[jj]>originarray[jj+1])
swap(originarray[jj],originarray[jj+1]);
}
ii--;
}
}
First, to properly test template code (at least with MSVC), you should instantiate it.
Moreover, if you try your code with some class that is in the std namespace, std::swap() can be picked by the compiler via ADL (Koenig) lookup.
Figuring if something wasn't broke, I'd break it, I decided to specialize a class I had so that it could be templated between float and double precision automagically.
I have the following [simplified] class declaration:
// Quatcam.h
#pragma once
#include <boost/math/quaternion.hpp>
#include <boost/numeric/ublas/matrix.hpp>
template<typename FloatType>
class QuaternionCamera
{
public:
QuaternionCamera();
void applyTranslation(boost::numeric::ublas::vector<FloatType> translationVector);
boost::numeric::ublas::matrix<FloatType> getTranslationMatrix();
protected:
boost::numeric::ublas::vector<FloatType> m_location;
boost::math::quaternion<FloatType> m_orientation;
};
I have defined the member functions in a .cpp file:
//Quatcam.cpp
#include "Quatcam.h"
using namespace boost::numeric::ublas;
template<typename FloatType>
QuaternionCamera<FloatType>::QuaternionCamera()
: m_location(3),
m_orientation(1,0,0,0)
{
m_location[0] = m_location[1] = m_location[2] = 0;
}
template<typename FloatType>
void QuaternionCamera<FloatType>::applyTranslation(boost::numeric::ublas::vector<FloatType> translationVector)
{
m_location += translationVector;
}
template<typename FloatType>
boost::numeric::ublas::matrix<FloatType> QuaternionCamera<FloatType>::getTranslationMatrix()
{
boost::numeric::ublas::matrix<FloatType> returnMatrix = boost::numeric::ublas::identity_matrix<FloatType>(4,4);
boost::numeric::ublas::vector<FloatType> invTrans = -m_location;
returnMatrix(3,0) = invTrans[0];
returnMatrix(3,1) = invTrans[1];
returnMatrix(3,2) = invTrans[2];
return returnMatrix;
}
This code by itself will happily compile into a .lib or .obj file, but attempting to use the class in situ results in linker errors. Here is my example main.cpp attempting to use the class:
#include "Quatcam.h"
#include <boost/numeric/ublas/io.hpp>
#include <iostream>
int main(int argc, char** argv)
{
QuaternionCamera<float> qcam;
boost::numeric::ublas::vector<float> loc(3);
loc[0] = 0;
loc[1] = 5;
loc[2] = 0;
qcam.applyTranslation(loc);
boost::numeric::ublas::matrix<float> qtm = qcam.getTranslationMatrix();
std::cout << "qtm: "<< qtm << std::endl;
return 0;
}
This code fails to link with an error for missing symbols for getTranslationMatrix and applyTranslation. I assume this is because I haven't technically specified a full specialization of the functions for the type float.
Question(s)
Given that the behavior is the same for any atomic input type (float, double, even int, etc...) and only affects the precision of the answers.
Is there a way to force the compiler to emit specializations for all of them without having to;
move all of the function definitions into the header file, or;
explicitly create specializations for all data types that would presumably involve a lot of copypasta?
Recommended links
Why can templates only be implemented in the header file?
Why do C++ template definitions need to be in the header?
Recommended Practice
Instead of moving the definitions from the .cpp to the header, rename the .cpp to .tpp and add #include "Quatcam.tpp" at the end of Quatcam.h.
This is how you typically split up the template declarations, and their definitions, while still having the definitions available for instantiation.
Note: If you follow this road, you should not compile the .tpp by itself, as you were doing with the .cpp.
Explicit Instantiation
You can explicitly instantiate the templates in question in your .cpp to provide them for the linker, but that requires that you know the exact types that you'd require an instantation of.
This means that if you only explicitly instantiate QuaternionCamera<float>, you'd still get a linker error if main.cpp tries to use QuaternionCamera<double>.
There's no way of forcing instantiation of all "atomic input types", you'll have to write them all out explicitly.
template class QuaternionCamera<float>; // explicit instantiation
template class QuaternionCamera<double>; // etc, etc...
You should put these functions into the header file, not into the .cpp source.
The compiler only creates function instantiations after the template argument deduction is complete. The resulting object file will contain a compiled function for each type that the template was used with.
However, .cpp files are compiled separately. So, when you compile Quatcam.cpp, the compiler doesn't find any instantiations for this type, and doesn't create a function body. This is why you end up with a linker error.
To put it simply, this is how your header should look like:
template<typename T>
class Foo {
void Print();
T data;
};
// If template arguments are specified, function body goes to .cpp
template<>
void Foo<float>::Print();
// Template arguments are incomplete, function body should remain in the header
template<typename T>
void Foo<T>::Print() {
std::cout << data;
}
And this should to the .cpp source:
template<>
void Foo<float>::Print() {
std::cout << floor(data);
}
namespace n1 {
namespace n2 {
...
int myfunc(void)
{
return 1;
}
class myclass {
..
};
}
}
I thought it is possible to define a function this way, and access it both from 'myclass' and its derivatives. However gcc doesn't even want to compile this code:
multiple definition of `n1::n2::myfunc()'
This function is the only one here, what am I missing?
Thanks.
You need to either mark the function inline to avoid breaking the one definition rule, or place the implementation in a .cpp file, and leave only the declaration in the header.
I recently asked this question about how to simulate type classes in D and suggested a way to do this using template specialization.
I discovered that D doesn´t recognize template specialization in a different source file. So I couldn´t just make a specialization in a file not included from the file where the generic function is defined. To illustrate, consider this example:
//template.d
import std.stdio;
template Generic(A) {
void sayHello() {
writefln("Generic");
}
}
void testTemplate(A)() {
Generic!A.sayHello();
}
//specialization.d
import std.stdio;
import Template;
template Generic(A:int) {
void sayHello() {
writefln("only for ints");
}
}
void main() {
testTemplate!int();
}
This code prints "generic" when I run it. So I´m asking whether there is some good workaround, so that the more specialized form can be used from the algorithm.
The workaround I used in the question about Type classes was to mixin the generic functions after importing all files with template specialization, but this is somewhat ugly and limited.
I heard c++1x will have extern templates, which will allow this. Does D have a similar feature?
I think I can give a proper answer to this question. No.
What you are trying to do is highjack the functionality of template.d (also case should match on file and import Template, some operating systems it matters). Consider:
// template.d
...
// spezialisation.d
import std.stdio;
import template;
void main() {
testTemplate!int();
}
Now someone updates the code:
// specialization.d
import std.stdio;
import template;
import helper;
void main() {
testTemplate!int();
getUserData();
}
Perfect right? well inside helper:
// helper.d
getUserData() { ... }
template Generic(A:int) {
A placeholder; //...
}
You have now changed the behavior of specialization.d just from an import and in fact this would fail to compile as it can not call sayHello. This highjack prevention does have its issues. For example you may have a function which takes a Range, but the consumer of your library can not pass an array unless your library imports std.array since this is where an array is "transformed" into a range.
I do not have a workaround for your problem.
Michal's comment provides a solution to the second form of highjacking, where say specialization.d tried to highjack getUserData
// specialization.d
import std.stdio;
import template;
import helper;
alias helper.getUserData getUserData;
string getUserData(int num) { ... }
void main() {
testTemplate!int();
getUserData();
}
IIRC; as a general matter in D, symbols in different files can't overload because the full name of a symbol includes the module name (file name) making them different symbols. If 2 or more symbols have the same unqualified name and are from 2 or more files, attempting to use that unqualified symbol will result in a compile error.
Been away from C++ for a few years and am getting a linker error from the following code:
Gene.h
#ifndef GENE_H_INCLUDED
#define GENE_H_INCLUDED
template <typename T>
class Gene {
public:
T getValue();
void setValue(T value);
void setRange(T min, T max);
private:
T value;
T minValue;
T maxValue;
};
#endif // GENE_H_INCLUDED
Gene.cpp
#include "Gene.h"
template <typename T>
T Gene<T>::getValue() {
return this->value;
}
template <typename T>
void Gene<T>::setValue(T value) {
if(value >= this->minValue && value <= this->minValue) {
this->value = value;
}
}
template <typename T>
void Gene<T>::setRange(T min, T max) {
this->minValue = min;
this->maxValue = max;
}
Using Code::Blocks and GCC if it matters to anyone. Also, clearly porting some GA stuff to C++ for fun and practice.
The template definition (the cpp file in your code) has to be included prior to instantiating a given template class, so you either have to include function definitions in the header, or #include the cpp file prior to using the class (or do explicit instantiations if you have a limited number of them).
Including the cpp file containing the implementations of the template class functions works. However, IMHO, this is weird and awkward. There must surely be a slicker way of doing this?
If you have only a few different instances to create, and know them beforehand, then you can use "explicit instantiation"
This works something like this:
At the top of gene.cpp add the following lines
template class Gene<int>;
template class Gene<float>;
In if(value >= this->minValue && value <= this->minValue) the second minValue should be maxValue, no?
Echo what Sean said: What's the error message? You've defined and declared the functions, but you've not used them in anything anywhere, nor do I see an error (besides the typo).
TLDR
It seems that you need an Explicit Instantiation i.e. to actually create the class. Since template classes are just "instructions" on how to create a class you actually need to tell the compiler to create the class. Otherwise the linker won't find anything when it goes looking.
The thorough explanation
When compiling your code g++ goes through a number of steps the problem you're seeing occurs in the Linking step. Template classes define how classes "should" be created, they're literally templates. During compile time g++ compiles each cpp file individually so the compiler sees your template on how to create a class but no instructions on what "classes" to create. Therefore ignores it. Later during the linking step the g++ attempts to link the file containing the class (the one that doesn't exist) and fails to find it ultimately returning an error.
To remedy this you actually need to "explicitly instantiate" the class by adding the following lines to Gene.cpp after the definition of the class
template class Gene<whatever_type_u_wanna_use_t>;int
Check out these docs I found them to be super helpful.