cast template

Is it possible to cast a string to a template?
 
  x= (T) y; 

where T is my template type, y is a string and x is of type T.
No templates (not even class templates) are types; type casting fundamentally cannot do this.

If you want to typecast an expression to a particular instantiation of a class template, this is possible, e.g.:
1
2
3
4
5
6
7
template <typename T> 
class A { T i; };
struct B { explicit operator A<int>() const { return A<int>{}; } };
int main() {
    B my_b;
    static_cast<A<int>>(my_b);
}


After a little bit of thought, this looks like an XY problem ( http://xyproblem.info ) . Can you better explain what your goal is?
Is (for example) boost::lexical_cast<> what you're looking for?
http://www.boost.org/doc/libs/1_64_0/doc/html/boost_lexical_cast.html
Last edited on
I have a string that is composed by an unknowed number of template variables and i want to store them.
I tried to divide the string and to cast each part but i am not able to do this.
Is there any way to avoid the cast?
thank you for your time :-)
stringstream? Or have I (as is quite likely) got completely the wrong end of the stick.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

//=====================================================================

template <class T> vector<T> split( string s )
{
   vector<T> result;
   T value;

   stringstream ss( s );
   while ( ss >> value ) result.push_back( value );
   return result;
}

//=====================================================================

int main()
{
   string text;

   cout << "Integers:\n";
   text = "1 3 5 7 9";
   vector<int> ivec = split<int>( text );
   for ( int i : ivec ) cout << i << '\n';

   cout << "Doubles:\n";
   text = "2.0 4.0 6.0 8.0 10.0";
   vector<double> dvec = split<double>( text );
   for ( double d : dvec ) cout << d << '\n';
}


Integers:
1
3
5
7
9
Doubles:
2
4
6
8
10
Topic archived. No new replies allowed.