Maxim Yarmolik
Maxim Yarmolik

Reputation: 107

Specialization of a template with enable_if in header file

So i want to make 2 functions: one for numbers(with template) and one for strings. Here's my best try:

Header:

class myIO
{
public:

    template<class Arithmetic,
        class = enable_if_t< is_arithmetic_v <Arithmetic>>
    >
    static Arithmetic Input();

    template<>
    static string Input<string, void>();
};

cpp:

template<class Arithmetic, class>
static Arithmetic myIO::Input()
{
    Arithmetic x;
    //...
    return x;
}

template<>
static string myIO::Input<string, void>()
{
    string x;
    //...
    return x;
}

This implementation works but if i want to use it with string i have to do string x = myIO::Input<string, void>();

And i would like to be able to write just <string> not <string, void>

Is that possible?

Upvotes: 1

Views: 676

Answers (2)

Maxim Yarmolik
Maxim Yarmolik

Reputation: 107

Here is the answer: .h:

class myIO
{
public:

    template<class Arithmetic,
        class = enable_if_t< is_arithmetic_v <Arithmetic>>
    >
    static Arithmetic Input();

    template<class String,
        class = enable_if_t< is_same_v<String, string> >
    >
    static string Input();
};

.cpp:

template<class Arithmetic, class>
static Arithmetic myIO::Input()
{
    Arithmetic x;
    // doing something
    return x;
}

template<class String, class>
static string myIO::Input()
{
    string x;
    // doing something
    return x;
}

p.s. i have actually tried a similar method - enable_if_t< typeid(String) == typeid(string), string > - but it didn't work

Upvotes: 1

Vladimir Nikitin
Vladimir Nikitin

Reputation: 181

You could do something like this

#include <iostream>
#include <string>
class A {
    public:
    template<typename T, typename U>
    static void func()
    {
        std::cout << "Do stuff\n";
    }

    template<typename T>
    static void func()
    {
        A::func<T, void>();
    }

};

int main()
{
    A::func<string>();
    return 0;
}

Upvotes: 0

Related Questions