2

I need to build my DLL project. The example code is OK, and the code is:

#ifdef MyDLL_EXPORTS
#define MyDLL_EXPORT __declspec(dllexport)
#else
#define MyDLL_EXPORT __declspec(dllimport)
#endif


class MyDLL_EXPORT arithmetic_operation
{
public:
    double add(double a, double b);
};

double arithmetic_operation::add(double a, double b)
{
    return a + b;
}

Then, I want to modify this code to a template code, and the modified code is:

#ifdef MyDLL_EXPORTS
#define MyDLL_EXPORT __declspec(dllexport)
#else
#define MyDLL_EXPORT __declspec(dllimport)
#endif

template <typename data>
class MyDLL_EXPORT arithmetic_operation
{
public:
    double add(data a, data b);
};

template <typename data>
double arithmetic_operation<data>::add(data a, data b)
{
    return a+b;
}

However, a bug is reported when compiling:

C2491: 'arithmetic_operation<data>::add': definition of dllimport function not allowed. 

What does this error means? How can I fix this bug?

Qiang Zhang
  • 820
  • 8
  • 32
  • Templates can't be exported. And it doesn't make sense to implement a template in a DLL anyway. See [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/) – Remy Lebeau Feb 24 '20 at 07:59
  • 1
    You don't need to export templated code, it is compiled at the moment you use it (i.e. _instantiate_ your template by making a call in client code) - much like inlined code works – mvidelgauz Feb 24 '20 at 08:06

0 Answers0