Ok, so I'm basically making a class that is supposed to be similar to
var in javascript. It's gonna be able to hold only four or five very specific types, and I was writing the constructor, and the constructor is exactly the same for all the types, but I don't want to use just a normal templated constructor, because then it will accept a bunch of types I don't necessarily want, right? So, I remembered that there is supposed to be a way to implement template classes outside of the header file by explicitly instantiating the template function or class in the header, and then implementing it in the
.cpp, however this makes it so only those types that you explicitly instantiated are able to be used. This is the exact behavior I want.
The only problem is that I have absolutely know idea how I would do that specifically for a function inside of a class, or for the constructor, because the class itself is not a template class, just the function.
I was wondering if anyone knew how that's supposed to work..? I would greatly appreciate some example specific to my situation.
My code would look something like this, I think.
var.hpp:
1 2 3 4 5 6 7 8 9 10 11 12
|
#pragma once
class var
{
// ...
template <int> var(int x); // explicit instantiation 1
template <float> var(float x); // explicit instantiation 2
template <std::string> var(std::string x); // explicit instantiation 3
// ...
};
|
var.cpp:
1 2 3 4 5 6 7 8
|
#include "var.hpp"
// ...
template <typename type>
var::var<type>(type value): _type(typeid(type)), _value(value) {}
// ...
|
main.cpp:
1 2 3 4 5 6 7 8 9 10
|
#include <vector>
#include <string>
#include "var.hpp"
int main()
{
var x( 2356 ); // fine
var y( std::string("hello!") ); // fine
var z({ 12 , 345, 66 }); // not fine! error!
}
|