Function for templates

Hello,

I have a template where there are some functions which are correct only for some of the data types and not for all. So, I want to make them available only for those data types and not for all in general. How do I do that?
Can't do it with templates alone, however you can make a series of inline functions that call the template.

1
2
3
4
5
6
7
8
9
10
// assuming your function works with int,long,short but not float/double:
inline void func(int v)   { func2(v); }
inline void func(long v)  { func2(v); }
inline void func(short v) { func2(v); }

// make this protected/private to prevent it being called with undesired types
template <typename T> void func2(T v)
{
 // do whatever
}
I think you can using templates.
You seperate the template into a header and a cpp file and do explicit instantiations of the
required functions in the cpp file.

Include the header as normal, and compile the cpp file. Any types for which there is no
instantiation in the cpp file will cause a linker error.
Also consider not using templates at all and just making overloads, if the functions are small.

Or, consider using type traits to force compile errors for types that are not supported.

I have a class template and want to limit function for some data type so.... can't simply overload..... have to do for everything else as well then..

@Disch..... this function make use of class members... how will I incorporate that?
Does anyone have any idea about this?
you can use template specialization
I am already using template specialization but still having problem..

Here is the actual problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

template<typename T> class ABC
{
    T x;
    void test1()
    {
         
    }
   
    void test2()
    {

    }

    void test3()
    {
    
    }
};


All three function make use of x in them. But I test2 and test3 only for certain data types and not for all.

I want want to make a separate class of only these two function. Is there any better idea to do something about it?
Try to specialize like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template <typename T>
class ABC
{
    T x;
    void test1();
};

template <>
class ABC<The_type_you_want>
{
    The_type_you_want x;
    void test1();
    void test2();
    void test3();
};

or try somethink like this:
1
2
3
4
5
6
// (in the class)
void test2()
{
    if ( strcmp(typeid(T).name(),"The type you want") )
        throw "I don't want this! >:^(";
} 
Last edited on
Still it doesn't help much.... It still giving warning while compiling.... I want to remove those warnings as well. Is it possible some way?
Can you post an example that is closer to what you are trying to do? Like what types you want to allow, etc.?
Topic archived. No new replies allowed.