biagiop1986
biagiop1986

Reputation: 405

Multiple Template Instantiation

I'm designing a CUDA-C++ library with template classes. There are template functions my classes use, and they are invisible to main as well as the user. I need to specialize them explicitly because of the two steps of compiling to be performed, otherwise I'd get an "unresolved external" error when linking. Being this classes used in main.cpp, there's no way (I guess...) to tell nvcc what types are going to be used in tha main program, so I thought of using some macros to specialize them. Here's a simplified versione of the code:

//CUDA_functions.h
// CUDA functions declared here and included in files that will be compiled 
// with g++. Those functions are implemented in .cu files, compiled with nvcc
template <typename T>
void foo1(T x);
template <typename T>
void foo2(T x);
template <typename T>
void foo3(T x);

//fileA.h - included in main.cpp
#include "CUDA_functions.h"
template <typename T>
class A {
    // it uses foo1 & foo2 inside
}

//fileB.h - included in main.cpp
#include "CUDA_functions.h"
template <typename T>
class B {
    // it uses foo1 & foo3 inside
}

//macros.h
#define _USE_CLASS_A(T) template void foo1(T); \
    template void foo2(T); /**/
#define _USE_CLASS_B(T) template void foo1(T); \
    template void foo3(T); /**/

//user_spec.cu - template specializations by user. This is the first file to be
//             - compiled and it doesn't know what classes are going to be used
// say, user wants to use classes A & B: HERE THE ERROR RAISES!
#include "macros.h"
_USE_CLASS_A( int );
_USE_CLASS_B( int );

When I compile this code with Visual Studio, I get a warning about the double explicit instantiation (foo1), but when I compile it with g++ warning becomes an error! I can't write macros like

#define _USE_FOO1(T) template void foo1(T) /**/
#define _USE_FOO2(T) template void foo2(T) /**/
#define _USE_FOO3(T) template void foo3(T) /**/

because the user doesn't have to worry about the existence of those functions and I'd like to specialize a list of them based on what class he/she is going to use. Last but not least, I found nothing about a "conditional specialization" of template. What can I do to solve? Thanks to everyone would be so nice to answer. Bye.

Upvotes: 0

Views: 475

Answers (1)

CygnusX1
CygnusX1

Reputation: 21779

Is it for host code or device code? I believe CUDA does not support linking for device code. Linking template functions in host code has always been a bit fishy, CUDA or no CUDA.

Instead of having your hands dirty with macros -- how about putting them in a header, inside of namespace detail? By convention, detail namespace indicates library internal stuff that you shouldn't ever access as a user.

Upvotes: 1

Related Questions