vendredi 30 octobre 2015

Templating template instantiation in different file

I'm aware that the following works:

test.h

#pragma once

#include <string>

class testclass
{
private:
    std::string _data;
public:

    template<class T> 
    testclass(const T&);

};

test.cpp

#include "test.h"

template testclass::testclass(const int&);
template testclass::testclass(const long&);

//function can be called only with `int` and `long`
template<class T> 
testclass::testclass(const T &num)
    : _data(std::to_string(num))
{}

So this is a successful way of splitting the declaration and implementation of a template function, but it has some downsides. One of them is having to hardcode all the types with which you want your function to be called and that's a drag. And if the function is quite small, you end up having written more code than you would have if you hadn't templated it...

I was wondering if something like this is possible:

test.cpp

#include "test.h"

template<class T2> //bogus syntax, but here the point of interest
template testclass::testclass(const T2&);

template<class T> 
testclass::testclass(const T &num)
    : _data(std::to_string(num))
{}

Aucun commentaire:

Enregistrer un commentaire